Understanding method_added for class methods

前端 未结 1 860
日久生厌
日久生厌 2020-12-28 17:15

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.incl         


        
相关标签:
1条回答
  • 2020-12-28 17:39

    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 讨论(0)
提交回复
热议问题