5 Apr
Ruby Pocket Session #3 - Callbacks
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 by dint of. 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
rank 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.
