下面是相同語法的最小實現,這是Ruby配置管理的典型代碼。
這裏的關鍵是htpassword
是一種接受兩個參數 - 一個字符串和一個塊的方法。 Ruby中的塊捕獲它們在其中定義的範圍(語法範圍),因此您在配置器中使用instance_eval
在其作用域內運行塊,該塊已定義了user
和password
方法,這些方法都是簡單的設置器。配置器不能使用更直觀的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
謝謝,這是一個很好的解釋,真正解決了問題。在我授予最佳答案之前,您能否解釋爲什麼參數不是逗號分隔的? – jshthornton
如果方法中的最後一個參數是塊,則可以在方法調用後立即寫入。所以如果你在塊之前有兩個參數,它會是'htpassword「foo」,「bar」do',或者與可選的parens - 'htpassword(「foo」,「bar」)做' –
嗯,非常有趣。紅寶石是一個異想天開的野獸。享受最好的回答:) – jshthornton