ruby - How do have a class method that redefines other class methods? -
i want wrap class methods module logging, this:
module somemodule def self.foo puts "bar" end class << self somemodule.methods(false).each |method| alias_method "old_#{method}".to_sym, method define_method method |*args| puts "called method: #{method}" send "old_#{method}", *args end end end end somemodule.foo #-> called method: foo #-> bar that works perfectly. if wanted wrapping happen when called method? how make happen when call
module somemodule def self.foo puts "bar" end def self.add_logging_to_all_methods #??? end end somemodule.add_logging_to_all_methods somemodule.foo #-> called method: foo #-> bar
i’m not going ask want for, here is:
module somemodule def self.foo puts "bar" end def self.add_logging_to_all_methods eigenclass = class << self; self; end methods(false).each |method| eigenclass.class_eval alias_method "old_#{method}".to_sym, method define_method method |*args| puts "called method: #{method}" send "old_#{method}", *args end end end end end somemodule.add_logging_to_all_methods somemodule.foo be aware adds “logging” add_logging_to_all_methods, after invoking it, if invoke once, should not see wrong.
what eigenclass means “instance” add methods foo , add_logging_to_all_methods. returning self inside class << self; end block i’m getting instance. ask block evaluated in context of instance, more or less same previous method.
there may easier way it.
Comments
Post a Comment