Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use class << self in ruby?

Tags:

ruby

Can you explain why the developer is using class << self to add a methods to the base class?

base.rb from the GeoPlanet Gem

module GeoPlanet
  class Base
    class << self
      def build_url(resource_path, options = {})
    end
  end
end
like image 719
jspooner Avatar asked Dec 08 '22 01:12

jspooner


1 Answers

Because he doesn't know that

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

would work just as well?

Well, they aren't 100% equivalent: if GeoPlanet doesn't exist, then the original snippet will create the module, but my version will raise a NameError. To work around that, you'd need to do this:

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

Which will of course raise a NameError, if Base doesn't exist. To work around that, you'd do:

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

However you look at it, there's no need to use the singleton class syntax. Some people just simply prefer it.

like image 172
Jörg W Mittag Avatar answered Dec 24 '22 01:12

Jörg W Mittag