Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding method_added for class methods

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?

like image 336
GeorgieF Avatar asked Jan 25 '11 22:01

GeorgieF


People also ask

When to use class methods Python?

You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.

How do you define a class method in Ruby?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

What is the class method?

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod. The difference between a static method and a class method is: Static method knows nothing about the class and just deals with the parameters.


1 Answers

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!

like image 63
Johannes Fahrenkrug Avatar answered Sep 28 '22 05:09

Johannes Fahrenkrug