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

标签 ruby-on-rails ruby

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

最佳答案

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

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

相关文章:

ruby-on-rails - Ruby - 为什么这个回调函数不起作用

ruby-on-rails - Rails Assets 管道在开发中连接 application.css 和 js,但在生产中不连接

python - Python 的 os.walk 的 Ruby 等价物是什么?

ruby-on-rails - roo 库是否适用于 Ruby 2.0?

ruby-on-rails - 限制 Rails 中的两个循环

ruby-on-rails - nginx limit_req 速率限制问题 - 文档说明?

ruby-on-rails - rails : Authenticate before routing

ruby - 从 ruby​​ 内部加密数据包,无需依赖 Knife

ruby-on-rails - 如何使用 Grape 和 MongoDB 在 Ruby on Rails 中正确测试 'post'(创建)方法

ruby - 找不到所需的 'adsf' gem,这是查看命令所必需的