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

2

8

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?

Kala answered 5/4, 2012 at 22:43 Comment(2)
One of them has one extra letter than the other? :) What do you mean by "is there a difference"? One is a class, one is a module, and in both you are entering the eigenclass.Chromatic
I think I mean to ask, when would you use one over the other. I edited the question to reflect that.Kala
C
7

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.

Chromatic answered 5/4, 2012 at 23:13 Comment(0)
L
2

The difference between a Module and a Class is that you can make an instance of a Class, but not a Module. If you need to create an instance of Helper (h = Helper.new) then it should be a class. If not, it is probably best to remain a module. I'm not sure how the rest of your code is relevant to the question; whether you have class methods on a Module or a Class is not relevant to whether you need to create instances of that object.

Lear answered 5/4, 2012 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.