Vignesh Jayavel

Rails ActiveRecord Callback Chains

I am working with a RoR backend that is basically Rails 2.3.8 based. Yes, it is an outdated version, but still you have to get things done. ActiveRecord callbacks are one of the most powerful functionalities of the Rails ActiveRecord class. If understood correctly, they make good weapons for the developers. This is the order of callbacks in Rails 2.3.8

###Creating an Object

###Updating an Object

###Destroying an Object

##Diving deep into ActiveRecord callbacks

To dive deep into callbacks we should know the callbacks that are registered on a model.

###Getting all the callback chain methods

Model.methods.select {|method| method.to_s.include? "callback_chain"}

This lists all the possible callback chains for a model class (no matter whether there really exists a registered callback or not)

Technically this is an array of symbols which are callback chain method names.

###Getting all the callbacks and the actual method names

Say you have a callback chain and now you need to know the methods that are part of that callback chain. This trick will give you the exact detail

Model.callback_chain_method.map(&:method)

###Getting all the callback chains and the callback method names

Model.methods.select{|method| method["callback_chain"]}.each do |callback_chain|
	puts "####{callback_chain.to_s} : "
	puts Model.send(callback_chain).map(&:method).join("\n")
	puts "----------------"
end