active_record_defaults

Greetings,

I just put together a plugin that allows you to easily specify default values for AR models. This is useful when your defaults can’t (or you don’t want to) be specified by the database. I use it to populate attribute values from user-configurable defaults. Eg:

class Person < ActiveRecord::Base
defaults :name => ‘My name’, :age => 0

default :country do
Configuration.default_country
end
end

The default values are ignored if the attribute is given a specific value.

p = Person.new
p.name # “My name”

p = Person.new(:name => nil)
p.name # nil

There’s a few more examples here:
http://svn.viney.net.nz/things/rails/plugins/active_record_defaults/lib/active_record_defaults.rb

Install:

ruby script/plugin install
http://svn.viney.net.nz/things/rails/plugins/active_record_defaults/

Cheers,
-Jonathan.

Posted at http://agilewebdevelopment.com/plugins/activerecord_defaults :slight_smile:

Clever Jonathan Viney but why not at state defaults at migration. ?

Jonathan, I have a question.

Did you implement through after_initialize? If so this can have the negative side-effect of setting nil values to the default values after Find?

Or are you applying the defaults only through calls to New?

J

You can only define static defaults with migrations. This plugin allows the defaults to be determined when the model object is created. I use this to allow users to implement their own default values.

-Jonathan.

No, after_initialize is not used. I simply aliased the original initialize method, and called it from within the one I defined.

Existing records will remain unchanged. The default values are only used when creating new records.

-Jonathan.

Thanx Jonathan. Good stuff.

I have a class, with a great number of attributes - would it be possible to add a method call to assign all default values?

something like?

class Person < ActiveRecord::Base

defaults :set_defaults

def set_defaults

 name = 'My name'

 city = 'My city'

end

?

Jodi

I’ve just updated the plugin to allow you to do this.

class Person < ActiveRecord::Base
def defaults
# do whatever you like in here
end
end

I could remove the class methods for defining defaults and move to this method of simply having a defaults method on the model. This gives a bit more flexibility, but does make specifying simple defaults for one or two attributes take an extra line or two of code.

class Person < AR
defaults :name => ‘Jonathan’
end

vs

class Person < AR
def defaults
self.name = ‘Jonathan’
end
end

Thoughts?

-Jonathan.

Fabulous Jonathan.

I think that both options are valuable.

I prefer the readability of defaults :name => ‘Jonathan’. This is great for small assignments.

The new method is for large numbers of assignments.

I personally like both.

good dry stuff JV.

Jodi