David's Dingen

Mijn webloghonk

Attribute Defaults for Rails 3.0 and 3.1

Today I was having some time on my hands, and started searching the Ruby community for some useful things. I found Attribute Defaults (github) by Dimitrij Denissenko. This gem is for Ruby on Rails 3.0.x and 3.1.x for now, so if you are still on Rails2.x you’re out of luck. This very useful gem lets you setup defaults for Active Records with ease. No more def initialize or def set_defaults! I like Dimitrij’s solution above others because it follows the Rails principle of attr_protected and the likes. Here a quote from the Github README:

First, a simple case …

class Foo < ActiveRecord::Base
  attr_default :age, 18
  attr_default :last_seen do
    Time.now
  end
end
Foo.new # => age: 18, last_seen: '2010-09-15 10:30'

… or the same via mass-definition …

class Foo < ActiveRecord::Base
  attr_defaults :age => 18, :last_seen => lambda { Time.now }
end
Foo.new # => age: 18, last_seen: '2010-09-15 10:30'

So, as you can see, it’s a simple line of attr_defaults to define the default value of a field. More complex things can be done, be sure to read all about it in the README.

Comments