3

For example, if I have this callback:

after_create :notify_users

When that is called, how can I log something like "notify_users method is being called" in my log file?


I actually have several callbacks in my application. I know I can add something like puts 'notify_users method is being called' inside the notify_users method, but is there a way to log all callbacks automatically?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
sjsc
  • 4,552
  • 10
  • 39
  • 55
  • Possible duplicate of [Tracking/Logging ActiveRecord Callbacks](http://stackoverflow.com/questions/13089936/tracking-logging-activerecord-callbacks) – Jared Beck Jul 25 '16 at 05:44

2 Answers2

3
def notify_users
  logger.info "notify_users method is being called"
end
j-dexx
  • 10,286
  • 3
  • 23
  • 36
  • Thank you. I actually have several callbacks. Is there a way to do this dynamically for all callbacks being called instead of adding "logger.info .." for every callback? – sjsc Feb 24 '14 at 17:14
2

Think about it:

module Log
  def log *args
    args.each do |m|
      alias_method m.to_s + '_old', m

      define_method m do |*args|
        send(m.to_s + '_old', *args)
        puts "#{m} is called"
      end
    end
  end
end

class C
  def m1
    puts 'm1'
  end

  def m2
    puts 'm2'
  end

  extend Log

  log :m1, :m2
end

C.new.m1
C.new.m2

Provides:

m1
m1 is called
m2
m2 is called
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Thank you Speransky. My callbacks are actually called throughout many different files. Do you know if callback methods names can be called automatically somehow regardless of where they're called, or will I have to add a puts message inside every callback method? – sjsc Feb 24 '14 at 17:32
  • I appreciate that approach Speransky. I'll try it out. Thank you so much :) – sjsc Feb 24 '14 at 17:38