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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With