BrunoMiranda.com

Personal Blog about Software Engineering, Design, Travel & More

Writing a Rails Model Observers

Posted on September 11, 2007 at 04:06 PM

Model observers are useful for when you are trying to extend the class with functionally that is not directly connected to the DB model.

For example, you would like the app to send out an welcome email when a new user signs up. Emailing the member has no connection to the database table you are trying to model.

So you could create a MemberObserber as such:

ruby script/generate observer Member

That generator will create a file called member_observer.rb inside you app/models folder, which will look something like this:

class MemberObserver < ActiveRecord::Observer

end

You may now add a after_create method inside the class above. That method will be called after a member record is created.

class MemberObserver < ActiveRecord::Observer
    def after_save(member)
    AuthenticationMailer.deliver_welcome_email(member)
    end
end

If you name your observer the same as you model, rails will automatically set it to observe your model. You can however call it something different and manually specify what to observe, as such:

class MailerObserver < ActiveRecord::Observer
  observe  Member
  observer Reminder
end

Enjoy!

Tags: Rails
Hierarchy: previous, next

Comments

There are 0 comments on this post. Post yours →

Post a comment

Required fields in bold.

 

Visit the Archives →