10

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?

Community
  • 1
  • 1
berkes
  • 26,996
  • 27
  • 115
  • 206

1 Answers1

3

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.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • Apparently, they *do* [use the class elsewhere](https://github.com/discourse/discourse/blob/d41a8a21cc76fb50c0121942e7c04a1e8c34ffaa/app/controllers/user_avatars_controller.rb#L34). So it probably is not private, or else, it should be considered as such, but is not enforced. – berkes Nov 30 '15 at 13:35
  • My earlier command was erronous: the discourse user_avatars_controller *does* use it, but its code is probably not used or otherwise overriden, because, as you state correctly, this class is Private and cannot be called as such. – berkes Nov 30 '15 at 14:33