Ruby:在运行时观察方法(重新)定义

时间:2010-03-22 13:10:59

标签: ruby-on-rails ruby

我正在寻找一种方法(库或元编程技巧)来挂钩方法定义,这样我就可以扩展某些类并捕获它们的方法(重新)定义“事件”。

3 个答案:

答案 0 :(得分:3)

method_added 回调(遗憾的是,请参阅http://www.ruby-doc.org/core/classes/Module.html#M001662,没有文档)。您可以按如下方式使用它:

class Foo

  # define the callback...      
  def self.method_added(method_name)
    puts "I now have a method called #{method_name}"
  end

  # the callback is called on normal method definitions
  def foo
    # "I now have a method called foo" will be printed
  end

  # the callback is called on method definitions using define_method
  define_method :bar do
    # "I now have a method called bar" will be printed
  end

  # the callback is called on method definitions using alias and the likes
  alias :baz :foo # "I now have a method called baz" will be printed
end

答案 1 :(得分:1)

您是否尝试重写“define_method”?至少你可以捕获一些“运行时”方法定义?

答案 2 :(得分:1)

覆盖method_added。但请记住,如果您动态修改method_added中的方法,那么这些方法也会导致method_added被调用,因此您需要知道哪些方法是您所关注的用以避免无限递归。