[ANN] 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:


Building an e-commerce site with Rails?
http://www.agilewebdevelopment.com/rails-ecommerce

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

On 10/29/06, Benjamin C. [email protected] wrote:

end


Never be afraid to try something new. Remember, amateurs built the ark;
professionals built the Titanic!

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.

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.

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs