为什么在ruby中使用class << self?

jsp*_*ner 4 ruby

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

来自GeoPlanet Gem的base.rb.

module GeoPlanet
  class Base
    class << self
      def build_url(resource_path, options = {})
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 9

因为他不知道

def GeoPlanet::Base.build_url(resource_path, options = {}) end
Run Code Online (Sandbox Code Playgroud)

会工作得一样好吗?

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

module GeoPlanet
  def Base.build_url(resource_path, options = {}) end
end
Run Code Online (Sandbox Code Playgroud)

当然会提出一个NameError,如果Base不存在的话.要解决这个问题,你需要:

module GeoPlanet
  class Base
    def self.build_url(resource_path, options = {}) end
  end
end
Run Code Online (Sandbox Code Playgroud)

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


Bri*_*ian 6

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

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