为什么在ruby中使用class

时间:2022-07-26 22:29:01

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

你能解释为什么开发人员使用类<< self来向基类添加方法吗?

base.rb from the GeoPlanet Gem

来自GeoPlanet Gem的base.rb.

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

2 个解决方案

#1


9  

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:

好吧,它们不是100%等价:如果GeoPlanet不存在,那么原始代码片段将创建模块,但我的版本将引发NameError。要解决这个问题,你需要这样做:

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:

如果Base不存在,那么当然会引发NameError。要解决这个问题,你需要:

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.

无论你如何看待它,都不需要使用单例类语法。有些人只是喜欢它。

#2


6  

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.

我认为这只是风格/品味的问题。我喜欢使用类<< self方法,因为我有很多类方法要组合在一起或者提供某种与实例方法的视觉分离。

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

如果我的所有方法都是GeoPlanet作者所做的类方法,我也会使用这种方法。

#1


9  

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:

好吧,它们不是100%等价:如果GeoPlanet不存在,那么原始代码片段将创建模块,但我的版本将引发NameError。要解决这个问题,你需要这样做:

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:

如果Base不存在,那么当然会引发NameError。要解决这个问题,你需要:

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.

无论你如何看待它,都不需要使用单例类语法。有些人只是喜欢它。

#2


6  

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.

我认为这只是风格/品味的问题。我喜欢使用类<< self方法,因为我有很多类方法要组合在一起或者提供某种与实例方法的视觉分离。

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

如果我的所有方法都是GeoPlanet作者所做的类方法,我也会使用这种方法。