Why use the << self in ruby ​​class?

Can you explain why the developer uses class << self to add methods to the base class?

base.rb from GeoPlanet Gem

 module GeoPlanet class Base class << self def build_url(resource_path, options = {}) end end end 
+4
source share
2 answers

Because he does not know that

 def GeoPlanet::Base.build_url(resource_path, options = {}) end 

will work just as well?

Well, they are not 100% equivalent: if GeoPlanet does not exist, then the source fragment will create a module, but my version will raise a NameError . To get around this, you will need to do this:

 module GeoPlanet def Base.build_url(resource_path, options = {}) end end 

Which, of course, raises a NameError if Base does not exist. To get around this, you would do:

 module GeoPlanet class Base def self.build_url(resource_path, options = {}) end end end 

However, you look at it; there is no need to use the syntax of the singleton class. Some people just prefer it.

+9
source

I think this is just a matter of style / taste. I like to use the class << self approach when I have many class methods that I want to combine together or provide some kind of visual separation from the instance methods.

I would also use this approach if all my methods were class methods, as the author of GeoPlanet did.

+6
source

All Articles