Ruby 鲁比:扩展自我

Ruby 鲁比:扩展自我,ruby,Ruby,在Ruby中,我理解了extend的基本思想。然而,在这段代码中发生了什么?具体来说,扩展了什么功能?这只是将实例方法转换为类方法的一种方便方法吗?为什么要这样做,而不是从一开始就指定类方法 module Rake include Test::Unit::Assertions def run_tests # etc. end # what does the next line do? extend self end 在模块中,self是模块类本身。比如说 puts se

在Ruby中,我理解了
extend
的基本思想。然而,在这段代码中发生了什么?具体来说,
扩展了什么功能?这只是将实例方法转换为类方法的一种方便方法吗?为什么要这样做,而不是从一开始就指定类方法

module Rake
  include Test::Unit::Assertions

  def run_tests # etc.
  end

  # what does the next line do?
  extend self
end

在模块中,self是模块类本身。比如说

puts self
将返回耙子 所以

基本上使Rake中定义的实例方法对其可用,因此您可以

Rake.run_tests

将实例方法转换为类方法是一种方便的方法。但是您也可以将其用作。

对我来说,将
扩展
视为
包含在singleton类(也称为meta或eigen类)中总是有帮助的

您可能知道,在singleton类中定义的方法基本上是类方法:

module A
  class << self
    def x
      puts 'x'
    end
  end
end

A.x #=> 'x'
module A
  class << self
    include A

    def x
      puts 'x'
    end
  end

  def y
    puts 'y'
  end
end

A.x #=> 'x'
A.y #=> 'y'

extend self
将所有现有的实例方法作为模块方法包括在内。这相当于说
扩展Rake
。另外,
Rake
是类
模块的对象

实现等效行为的另一种方法是:

module Rake
  include Test::Unit::Assertions

  def run_tests # etc.
  end

end 

Rake.extend(Rake)
这可用于使用私有方法定义自包含模块。

为了避免链接损坏,下面将重新发布由用户83510链接的模块(经其许可)。 不过,没有什么能比得上原创,所以只要他的链接继续有效,就使用它


→ 单身歌手 2008年11月18日 有些事情我就是不明白。比如大卫·鲍伊。或者南半球。但没有什么比Ruby的Singleton更让我吃惊的了。因为真的,这完全没有必要

以下是他们希望您对代码执行的操作:

require 'net/http'

# first you setup your singleton
class Cheat
  include Singleton

  def initialize
    @host = 'http://cheat.errtheblog.com/'
    @http = Net::HTTP.start(URI.parse(@host).host)
  end


  def sheet(name)
    @http.get("/s/#{name}").body
  end
end

# then you use it
Cheat.instance.sheet 'migrations'
Cheat.instance.sheet 'yahoo_ceo'
但这太疯狂了。与权力斗争

require 'net/http'

# here's how we roll
module Cheat
  extend self

  def host
    @host ||= 'http://cheat.errtheblog.com/'
  end

  def http
    @http ||= Net::HTTP.start(URI.parse(host).host)
  end

  def sheet(name)
    http.get("/s/#{name}").body
  end
end

# then you use it
Cheat.sheet 'migrations'
Cheat.sheet 'singletons'
为什么不呢?API更加简洁,代码更易于测试、模拟和存根,并且在需要时转换为适当的类仍然非常简单


((版权归chris Wanstrash所有)避免linkrot的另一种方法是使用类似wayback机器的东西--它保存网页的历史记录,不管怎样,我发现它在很多linkrot案例中都非常有用。为什么这种单例更有效?你的链接已经损坏了我的朋友。用一个到存档的链接更新了这个答案。Org这个答案是不充分的,因为它没有解释所讨论的关键字如何将实例方法变成类方法。它也没有解释什么是“更高效的单身”,或者
extend self
与此有什么关系。
require 'net/http'

# here's how we roll
module Cheat
  extend self

  def host
    @host ||= 'http://cheat.errtheblog.com/'
  end

  def http
    @http ||= Net::HTTP.start(URI.parse(host).host)
  end

  def sheet(name)
    http.get("/s/#{name}").body
  end
end

# then you use it
Cheat.sheet 'migrations'
Cheat.sheet 'singletons'