berkes
berkes

Reputation: 27563

What does a class definition inside a class << self do?

I know how you can add class methods and class-behaviour using self << class (eigenclass). But, when reading some source code, I saw another use:

class LetterAvatar
  class << self
    class Identity
    end
  end
end

How does this work? What does it do and when should one use it? What would be a (possibly more recognised) alternative way to write this?

Upvotes: 10

Views: 118

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

I think they did so because they did not need this class anywhere else.

Without opening the singleton class the flow would look as following (assuming every method defined in metaclass from original code would be prefixed with self.):

They could have defined the Identity as

class LetterAvatar
  class Identity
  end
end

and then use the class in self.generate method as follows:

class LetterAvatar
  # code omitted
  def self.generate
    identity = LetterAvatar::Identity.from_username(username)
    # code omitted
  end
  # other class level methods defined with `self.`
end

But why doing so if the Identity class is actually used only (and need not to be accessed anywhere else) in the singleton class (in generate)?

The solution is IMO very elegant, haven't seen anything like this before.

Upvotes: 3

Related Questions