Print Page

Wednesday, August 12, 2015

Rails callback sequence with observers and model inheritance

 Cleaning up a tangle of callbacks I need to know the order they fire in to guide my refactoring. I ran this experiment in a tiny rails app with Rails 4.0.9 and the 'rails-observers' gem to match a legacy app I am working on, upgrading soon.

I made a mini rails app with two models, one inheriting from the other:

class Thingy < ActiveRecord::Base
  after_create :thingy_created_callback
  def thingy_created_callback     
    puts "thingy_after_create_callback"
  end 
end

class SpecialThingy < Thingy   
  after_create :special_thingy_created_callback
  def special_thingy_created_callback 
    puts "special_thingy_after_create_callback"
  end 
end

Made an observer to observe each:

class ThingyObserver < ActiveRecord::Observer   
  observe Thingy   
  puts "ThingyObserver loaded"
  def after_create(thingy)
    puts "ThingyObserver.after_create"
  end
end


class SpecialThingyObserver < ActiveRecord::Observer   
  observe SpecialThingy   
  puts "SpecialThingyObserver loaded"   
  def after_create(thingy)
    puts "SpecialThingyObserver.after_create" 
  end 
end

When creating an instance of SpecialThingy at console, I see the results in this order:

thingy_after_create_callback
special_thingy_after_create_callback
SpecialThingyObserver.after_create
ThingyObserver.after_create

No comments:

Post a Comment