ActiveRecord Callbacks List

Viewed 17698

I've been going through the rails source for a while now, and I don't think there's a better way of getting the list of all callbacks other than: ActiveRecord::Callbacks::CALLBACKS – which is a constant list.

Meaning if you're using a gem like devise_invitable that adds a new callback called :invitation_accepted with the score :after and :before then ActiveRecord::Callbacks::CALLBACKS will not work.

Do you know of an easy fix, other than opening up rails modules and making sure there's an internal list of call-backs per model class?

6 Answers

I am going to propose most universal solution.

It works even when gems are declaring custom callbacks e.g. paranoia and after_real_destroy

To list all callbacks

Model.methods.select { |m| m.to_s.include? "callback" }.sort

Then you can get given callbacks if you type method name e.g.

Model._update_callbacks
Model._real_destroy_callbacks
Model._destroy_callbacks

If you list all callbacks, then you can find callback you need by checking @filter instance variable e.g.

require 'pp'
Activity._destroy_callbacks.each_with_index { |clbk,index| puts "#{index}-------\n#{clbk.pretty_inspect}" } ; nil 

# [...]

#<ActiveSupport::Callbacks::Callback:0x00007ff14ee7a968
 @chain_config=
  {:scope=>[:kind, :name],
   :terminator=>
    #<Proc:0x00007ff13fb825f8@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activemodel-4.1.16/lib/active_model/callbacks.rb:103 (lambda)>,
   :skip_after_callbacks_if_terminated=>true},
 @filter=
  #<Proc:0x00007ff14ee7ac10@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activerecord-4.1.16/lib/active_record/associations/builder/association.rb:135 (lambda)>,
 @if=[],
 @key=70337193825800,
 @kind=:before,
 @name=:destroy,
 @unless=[]>
4-------
#<ActiveSupport::Callbacks::Callback:0x00007ff14ee3a228
 @chain_config=
  {:scope=>[:kind, :name],
   :terminator=>
    #<Proc:0x00007ff13fb825f8@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activemodel-4.1.16/lib/active_model/callbacks.rb:103 (lambda)>,
   :skip_after_callbacks_if_terminated=>true},
 @filter=:audit_destroy,
 @if=[],
 @key=:audit_destroy,
 @kind=:before,
 @name=:destroy,
 @unless=[]>
5-------
Related