我知道如何使用self << class
(eigenclass)添加类方法和类行为.但是,在阅读一些源代码时,我看到了另一种用法:
class LetterAvatar
class << self
class Identity
end
end
end
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?它应该做什么以及什么时候应该使用它?写这个的(可能是更多公认的)替代方法是什么?
我认为他们这样做是因为他们在其他地方不需要这门课。
如果不打开单例类,流程将如下所示(假设原始代码中元类中定义的每个方法都以 为前缀self.
):
Identity
他们本可以将其定义为
class LetterAvatar
class Identity
end
end
Run Code Online (Sandbox Code Playgroud)
然后在方法中使用该类,self.generate
如下所示:
class LetterAvatar
# code omitted
def self.generate
identity = LetterAvatar::Identity.from_username(username)
# code omitted
end
# other class level methods defined with `self.`
end
Run Code Online (Sandbox Code Playgroud)
Identity
但是,如果该类实际上仅在单例类(在 中)中使用(并且不需要在其他任何地方访问),为什么要这样做呢generate
?
IMO 的解决方案非常优雅,以前从未见过这样的东西。
归档时间: |
|
查看次数: |
105 次 |
最近记录: |