了解class方法的method_added

时间:2011-01-25 22:51:02

标签: ruby metaprogramming dsl

我想在瞬间做一些魔术,并将类方法添加到某个类中。因此我尝试了以下方法:

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

这种方法适用于实例方法,类方法失败。我怎么解决这个问题?有什么建议吗?

1 个答案:

答案 0 :(得分:25)

您正在寻找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

享受!