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

最佳答案

有添加回调的方法(请参见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

关于ruby-on-rails - Ruby:在运行时监视方法(重新)定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2492403/

10-13 05:54