Ruby programmers typically use class << self
inside a class body to open up the class object's eigenclass, like so:
class Foo
class << self
# ...
end
end
However, I seldom see this equivalent form (assume that Foo
is already defined to be a class):
class << Foo
# ...
end
Is there a reason for preferring the first style to the second?
When using class << Foo
, or when defining explicitly def Foo.some_method(args)
you are repeating the name of the class.
Using class << self
is DRYer, and makes refactoring easier (changing the class name is done in one place, and does not have to be repeated in the code), as well as copy+paste to other classes/projects.
class Foo1
# ..
end
class << Foo # <- :(
#..
end