2009-11-14 65 views
103

在Ruby中,我理解了extend的基本思想。但是,這段代碼發生了什麼?具體來說,extend做什麼?這只是將實例方法變爲類方法的簡便方法嗎?你爲什麼要這樣做,而不是從一開始就指定類方法?Ruby:擴展自我

module Rake 
    include Test::Unit::Assertions 

    def run_tests # etc. 
    end 

    # what does the next line do? 
    extend self 
end 

回答

107

這是一個方便的將實例方法變爲類方法的方法。但你也可以用它作爲more efficient singleton

+2

爲什麼這種單身人士更有效率? – xuuso 2016-06-16 10:53:01

26

在模塊中,self是模塊類本身。因此,例如

puts self 

將返回耙 所以,

extend self 

基本上使得在提供給它的Rake定義的實例方法,所以你可以做

Rake.run_tests 
14

對於我來說,在單例類(也稱爲meta或eigen類)內部總是考慮extendinclude

你可能知道,單例類中定義的方法基本上是類方法:

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

A.x #=> 'x' 

現在我們知道,extendinclude模塊中的方法的單身類中,從而將它們公開爲類方法:

module A 
    class << self 
    include A 

    def x 
     puts 'x' 
    end 
    end 

    def y 
    puts 'y' 
    end 
end 

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

extend self包括所有現有的實例方法作爲模塊方法。這相當於說extend RakeRake也是類Module的一個對象。

另一種方式來實現等效的行爲將是:

module Rake 
    include Test::Unit::Assertions 

    def run_tests # etc. 
    end 

end 

Rake.extend(Rake) 

這可以用來定義自包含與私有方法的模塊。

8

爲了避免鏈接腐爛,由user83510鏈接的blog post of Chris Wanstrath將在下面轉發(經他的許可)。 儘管如此,沒有什麼比原創的更好,所以只要繼續工作,就使用他的鏈接。


→唱着單身 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 wanstrath))

+0

避免linkrot的另一種方式是使用類似於wayback機器的東西 - http://web.archive.org - 它保留了網頁的歷史記錄,我發現它在很多情況下都是有用的。 – 2013-05-13 22:52:55