Showing posts with label idiomatic. Show all posts
Showing posts with label idiomatic. Show all posts

Wednesday, 8 August 2007

Association Callbacks

Similiar to the normal callbacks that hook into the lifecycle of an Active Record object, you can also define callbacks that get trigged when you add an object to or removing an object from a association collection. Example:
class Project
has_and_belongs_to_many :developers, :after_add => :evaluate_velocity

def evaluate_velocity(developer)
...
end
end

It’s possible to stack callbacks by passing them as an array.

Possible callbacks are: before_add, after_add, before_remove and after_remove.

Should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with the before_remove callbacks, if an exception is thrown the object doesn’t get removed.

Thursday, 22 March 2007

Named Callbacks

Coming from a Java background I often find myself wanting to override constructors and other hooks. I should really pay more attention to the documentation.

Instead of:
class MyClass
def after_initialize
#Do Something...
end
end

Do:

class MyClass
after_initialize :do_something

def do_something
#Do Something...
end
end

Update 13/06/07:

Using named callbacks better conveys your intention, making your code more readable.
Similar article on The Rails Way

Wednesday, 21 March 2007

Active Record Constructors

Do not write your own initialiser to instantiate the object. e.g:
class MyClass < ActiveRecord::Base
def initialize(params)
@params = params
end
end

Instead do this:

my_object = MyClass.new(:params => params)
my_object.save

Or this:

MyClass.create :params => params

The above will automatically save the record to the DB.