了解为类方法添加method_ [英] Understanding method_added for class methods

查看:100
本文介绍了了解为类方法添加method_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在实例和类方法添加到某个类的那一刻做一些魔术.因此,我尝试了以下操作:

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?

推荐答案

您正在寻找的singleton_method_added:

you are looking for singleton_method_added:

module Magic
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def method_added(name)
      puts "instance method '#{name}' added"
    end  

    def singleton_method_added(name)
      puts "class method '#{name}' added"
    end
  end  
end

class Foo
  include Magic

  def bla  
  end

  def blubb
  end

  def self.foobar
  end
end

输出:

instance method 'bla' added
instance method 'blubb' added
class method 'foobar' added

享受!

这篇关于了解为类方法添加method_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆