开发者

Understanding method_added for class methods

开发者 https://www.devze.com 2023-02-06 22:50 出处:网络
I would like to do some magic in the moment instance and class methods are added to some class. Therefore I tried the following:

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 app开发者_运维技巧roach works well for instance methods, fails for class methods. How can I solve that? Any suggestions?


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

Output:

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

Enjoy!

0

精彩评论

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

关注公众号