tags:

views:

79

answers:

2

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
+4  A: 

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.

Jörg W Mittag
Ok so the example from GeoPlanet is a little funky, right? Your two examples are much more readable and I tend to go with the 'self.build_url' way.
jspooner
+2  A: 

I think it is simply a matter of style/taste. I like to use the class << self approach when I have a lot of class methods that I want to group together or provide some sort of visual separation from instance methods.

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

Brian