Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we need ClassMethods and InstanceMethods?

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
like image 406
Lai Yu-Hsuan Avatar asked Sep 18 '11 18:09

Lai Yu-Hsuan


People also ask

What is the difference between Classmethod and Staticmethod?

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.

What is the purpose of class methods?

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.

Why do we need static methods in Python?

Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.

When should you use a class 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.


2 Answers

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.

like image 159
Dave Newton Avatar answered Oct 26 '22 04:10

Dave Newton


Dependencies are taken care of. See the example provided here.

like image 29
Michael De Silva Avatar answered Oct 26 '22 04:10

Michael De Silva