Default values for ActiveRecord models.
Pull request Compare This branch is 30 commits ahead, 17 commits behind fnando:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
gemfiles Update gemika Sep 28, 2016
Gemfile Default gemfile for development Sep 28, 2016

has_defaults Build Status

Default values for ActiveRecord models.


In your Gemfile

gem 'has_defaults'

Now run

bundle install


Add the method call has_defaults to your model.

class Page < ActiveRecord::Base
  has_defaults :title => "New page", :body => "Put your text here"

Attributes will be set only if it's a new record and the attribute is blank.

Retrieve the default attribute with the default_for instance method:


You can pass Proc as attribute:

has_defaults :expires_at => proc { }

You can override the default attributes as follow:

Page.has_defaults_options = {:title => "Here's your new page", :body => "Write your page text"}


There are tests in spec. We only accept PRs with tests. To run tests:

  • Install Ruby 2.2.4
  • Create a local test database has_defaults_test in both MySQL and PostgreSQL
  • Copy spec/support/database.sample.yml to spec/support/database.yml and enter your local credentials for the test databases
  • Install development dependencies using bundle install
  • Run tests using bundle exec rspec

We recommend to test large changes against multiple versions of Ruby and multiple dependency sets. Supported combinations are configured in .travis.yml. We provide some rake tasks to help with this:

  • Install development dependencies using bundle matrix:install
  • Run tests using bundle matrix:spec

Note that we have configured Travis CI to automatically run tests in all supported Ruby versions and dependency sets after each push. We will only merge pull requests after a green Travis build.