ActiveRecord Hooks for Database Events in Ruby
ActiveRecord hooks add addition capability that developers may find very useful. These hooks run some code when you try to add, delete or update a database.
ActiveRecord has two different ways when it comes to hooks implementation: ActiveRecord::Observer and callbacks
ActiveRecord callbacks implemented as part of ActiveRecord::Base class and include: before_save, after_save among others. Here is an example of running after_create callback in ActiveRecord implementation.
class MyClass < ActiveRecord::Base
def after_create
puts %{Record was created}
end
end
my_class = MyClass.create(:name => ‘Title’) //This line will save an object of MyClass type and will call of after_create method.
ActiveRecord callbacks are good for single action and it is not very suitable for multiple actions. In order to accommodate multiple actions after certain event, you can start using ActiveRecord::Observer. It is available from the rails-observer gem. Observers can watch a single class in your code.
In order to implement Observer, you need to create new method of the class that inherit Observer Class as shown in the example below
class MyClass < ActiveRecord::Base
end
class MyClassObserver < ActiveRecord::Observer
observe MyClass
def after_create
puts %{Record was created}
end
end
my_class = MyClass.create(:name => ‘Title’) //This line will save an object of MyClass type and will call of after_create method
Please note that in order for Observer to fire an event, you need to add the following snippet of the code into application.rb file
config.active_record.observers = :class_observer
Please note: if you name your Observer class after method you try to observer, then you don’t need to include class you want to observer inside the method. We presented both ways in one example above.