了解类方法的 method_added
我想在实例和类方法添加到某个类中时做一些魔法。因此我尝试了以下方法:
module Magic
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def method_added(name)
puts "class method '#{name}' added"
end
def some_class_method
puts "some class method"
end
end
end
class Foo
include Magic
def self.method_added(name)
puts "instance method #{name} added"
end
end
这种方法对于实例方法效果很好,对于类方法则失败。我该如何解决这个问题?有什么建议吗?
I would like to do some magic in the moment instance and class methods are added to some class. Therefore I tried the following:
module Magic
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def method_added(name)
puts "class method '#{name}' added"
end
def some_class_method
puts "some class method"
end
end
end
class Foo
include Magic
def self.method_added(name)
puts "instance method #{name} added"
end
end
This approach works well for instance methods, fails for class methods. How can I solve that? Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找 singleton_method_added:
输出:
享受吧!
you are looking for singleton_method_added:
Output:
Enjoy!