I read the API for ActiveSupport::Concern. There are ClassMethods
and InstanceMethods
, we can put class methods in ClassMethods
.
But the M
's host can use the methods defined in M
, can't it? Why can't I just write:
module M
def self.x
end
def y
end
end
rather than:
module M
module ClassMethods
def x
end
end
module InstanceMethods
def y
end
end
end
Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state.
Class methods are used when we are dealing with factory methods. Factory methods are those methods that return a class object for different use cases. Thus, factory methods create concrete implementations of a common interface. The class method can be called using ClassName.
Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.
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.
You might be interested in Yehuda's take on this pattern. I think the reason for some of it is historical, since they're not really needed unless you're doing manually what Ruby will do automatically through include
and extend
.
Dependencies are taken care of. See the example provided here.
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