Search code examples
rubyclassmoduleself

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


Is there a difference in usage between

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

and

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

When would you use one over the other?


Solution

  • The class<<self seems to be a red herring, as the only difference here is a class versus a module. Perhaps you're asking "I want to create an object that I do not intend to instantiate, but which exists only as a namespace for some methods (and possibly as a singleton with its own, global, state)."

    If this is the case, both will function equally well. If there is any chance that you might want to create a derivative (another object inheriting the same methods) then you should use a class as it slightly is easier to write:

    class Variation < Helper
    

    instead of

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

    However, for just namespacing I would generally use a module over a class, as a class implies that instantiation will occur.