Is there an easy way to register methods called by an object in Ruby?

Is there a quick way to track methods called by an object? Often, when I work with a stone at a level just below my open interface, I encounter errors that are difficult to track. Ultimately, I end up tracing the object through the source code and keeping everything in my head.

But it would be nice to call something like #log_method_calls on the object, so that, say, all methods it #log_method_calls are printed in stdout or something like that. Is there any way to do this?

+7
source share
1 answer

There are several ways to do this, depending on the situation.

If you can create a new object instead of an observable, you can easily write an observer class using the method_missing method.

 class LogProxy def initialize obj @obj = obj end def method_missing(name, *args) puts "#{name} => #{args.to_s}" @desk.send(name, *args) end end 

If this is not possible, you can still use alias_method. This is a little trickier, but using Module.instance_methods you can bind each method to something.

Something like:

 module Logger def self.included(mod) mod.instance_methods.each do |m| next if m =~ /with_logging/ next if m =~ /without_logging/ mod.class_eval do define_method "#{m}_with_logging" do |*args| puts "#{m} called #{args.to_s}" self.send_without_logging "#{m}_without_logging", *args end alias_method "#{m}_without_logging", m alias_method m, "#{m}_with_logging" end end end end TargetClass.send(:include, Logger) 
+5
source

All Articles