extend self includes all the existing instance methods as module methods. This is equivalent to saying extend Rake. Also Rake is an object of class Module.
达到同等行为的另一种方法是:
module Rake
include Test::Unit::Assertions
def run_tests # etc.
end
end
Rake.extend(Rake)
为了避免链接腐烂,用户83510链接的 Chris Wanstrath 的博客文章在下面重新发布(经过他的许可)。
尽管如此,没有什么能打败原创者,所以只要他的链接继续工作,就要使用它。
→独唱
18 November 2008
有些事我就是不明白。比如 David Bowie。或者南半球。但是没有什么比 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'
But that’s crazy. Fight the power.
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'