Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 738
berkes Avatar asked Nov 30 '15 08:11

berkes


1 Answers

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.

like image 95
Andrey Deineko Avatar answered Sep 22 '22 21:09

Andrey Deineko