1

我正在编写或多或少地从为这个问题选择的解决方案中提取的方面代码,如下所示:

class Module
  def add_logging klass, *method_names
    method_names.each do |method_name|
      original_method = instance_method method_name
      define_method method_name do |*args, &blk|
        log.debug("#{klass}.#{method_name} called")
        original_method.bind(klass).call(*args, &blk)
      end
    end
  end
end

另一篇文章中的解决方案不需要 klass 参数,但它仅适用于实例方法,而我希望这样调用我的代码:

module MyModule
  def MyModule.module_method
    p "hello"
  end
  class << self
    add_logging self, :module_method1
  end
end

不幸的是,当我运行这段代码时,我得到了in 'bind': singleton method called for a different object (TypeError). 看到我self在块的上下文中传递class << self,我不明白为什么上面代码中的绑定调用认为它没有绑定到完全相同的元类。

4

1 回答 1

2

这应该适合你:

class Module
  def add_logging(*method_names)
    method_names.each do |method_name|
      original_method = method(method_name).unbind
      define_singleton_method(method_name) do |*args, &blk|
        puts "#{self}.#{method_name} called"
        original_method.bind(self).call(*args, &blk)
      end
    end
  end
end

# class method example
module MyModule
  def self.module_method1
    puts "hello"
  end

  add_logging :module_method1
end

MyModule.module_method1

# output:
#
# MyModule.module_method1 called
# hello
于 2012-01-19T20:13:47.777 回答