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)
Dutow
source share