Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Mar 21

Ruby Pocket Session #3 - Callbacks

Posted by Massimo Sgrelli in Ruby on Rails - no comments digg this add to delicious

Active Records is the standard way that Rails provides to let your source code interact with databases. Active Records make available some standard callback functions to interact with their core tasks. Through callbacks you can intercept actions on databases, to perform some extra code before and after those actions. I found this topics interesting while refreshing my Ruby basics on the Ruby Pocket Reference and then I decided to go deeper through “Pro ActiveRecord – Databases with Ruby and Rails” (Amazon). I discovered this book some months ago reading Ruby Inside blog by Peter Cooper.

There are 2 ways to add a callback to your code:

  • overwriting the method
  • using macros

The best way to go through this, is using macros because of an inheritance hierarchy issue.

I’ll show a small example. Let’s suppose we have to define a Party and Customer model classes and we want to write a log when they have saved on the database:

Defining a callback using overwriting


class Party < ActiveRecord::Base
  def after_save
    writelog_party_saved
  end
end

class Customer < Party
  def after_save 
    writelog_customer_saved
  end
end

Defining a callback using macro


class Party < ActiveRecord::Base
  after_save :writelog_party_saved
end

class Customer < Party
  after_save :writelog_customer_saved
end

Using macros you preserve the inheritance chain of calls. So in the first case when you save a Customer record, no Party log is written. In the second case both callbacks are called, so the program writes a log for the Party record and one for the Customer record.

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory