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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With