2015-05-13 148 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