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

Go To StackoverFlow.com

6

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?

2012-04-05 22:43
by Andres Riofrio
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 - Phrogz 2012-04-05 23:02
I think I mean to ask, when would you use one over the other. I edited the question to reflect that - Andres Riofrio 2012-04-05 23:04


4

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.

2012-04-05 23:13
by Phrogz


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.

2012-04-05 23:14
by Myrddin Emrys
Ads