开发者

ruby - is there a way to add code to run after each method definition

I understand that def is a keyword and can't be ove开发者_Python百科rridden.

But is there a way to call a method when a method gets registered with a class(passing in the name of the method being created?)


That's what the Module#method_added hook method is for:

module Foo
  def self.method_added(meth)
    p meth
  end

  def bar; end
end

# :bar


To create a mixin with that hook:

module Foo
  def method_added(method_name)
    puts "method #{method_name} added"
  end
end

class Bar
  extend Foo

  def some_method
  end
end

Notice that method_added is class method (strictly class Class instance instance method sic!), since it is defined in Module class. So we have to add it with extend so it goes to Bar metaclass.


If I understand your question correctly,

class_instance.send(method_name)

should do it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜