Using the << self class, when to use classes or modules?

Is there any difference in use between

 class Helper class << self # ... end end 

and

 module Helper class << self # ... end end 

When do you use one over the other?

+6
source share
2 answers

class<<self seems like a red herring since the only difference here is the class versus module. Perhaps you are asking: "I want to create an object that I am not going to create, but which exists only as a namespace for some methods (and, possibly, as a singleton with its global state)."

If so, both will work equally well. If it is likely that you want to create a derivative (another object that inherits the same methods), then you should use a class, since it is a little easier to write:

 class Variation < Helper 

instead

 module Helper module OwnMethods # Put methods here instead of class << self end extend OwnMethods end module Variation extend Helper::OwnMethods 

However, for a simple namespace, I would usually use a module on the class, since the class implies that an instance will be executed.

+4
source

The difference between a module and a class is that you can instantiate the class, but not the module. If you need to create an instance of Helper (h = Helper.new), then it must be a class. If not, it is best to remain a module. I'm not sure how the rest of your code relates to the question; whether you have class methods in a module or class, it doesn’t matter if you need to instantiate this object.

+2
source

Source: https://habr.com/ru/post/912545/


All Articles