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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With