2015-05-13 197 views
1

我試圖找出這個塊是如何工作的抓紅寶石廚師塊

htpasswd "/etc/nginx/htpassword" do 
    user "foo" 
    password "bar" 
end 

我看到這種風格的代碼,很多廚師烹飪書。 我對ruby很新,就像超級新手一樣,但是在其他語言方面有很多經驗。

我想我已經研究出htpasswd是一個proc?但什麼是我如何使用文件名,以及如何分配工作user "foo"

回答

1

下面是相同語法的最小實現,這是Ruby配置管理的典型代碼。

這裏的關鍵是htpassword是一種接受兩個參數 - 一個字符串和一個塊的方法。 Ruby中的塊捕獲它們在其中定義的範圍(語法範圍),因此您在配置器中使用instance_eval在其作用域內運行塊,該塊已定義了userpassword方法,這些方法都是簡單的設置器。配置器不能使用更直觀的user = "foo"語法,因爲這隻會聲明塊內的局部變量。

class Configurator 
    def user(username) 
    @user=username 
    end 

    def htpassword(filename, &block) 
    @filename=filename 
    instance_eval(&block) 
    end 

    def run 
    puts "User = #{@user}, filename = #{@filename}" 
    end 
end 




c=Configurator.new 

c.htpassword "thefilename" do 
    user "theuser" 
end 

c.run 
#>User = theuser, filename = thefilename 
+0

謝謝,這是一個很好的解釋,真正解決了問題。在我授予最佳答案之前,您能否解釋爲什麼參數不是逗號分隔的? – jshthornton

+0

如果方法中的最後一個參數是塊,則可以在方法調用後立即寫入。所以如果你在塊之前有兩個參數,它會是'htpassword「foo」,「bar」do',或者與可選的parens - 'htpassword(「foo」,「bar」)做' –

+0

嗯,非常有趣。紅寶石是一個異想天開的野獸。享受最好的回答:) – jshthornton