我想弄清楚这个块是如何工作的
htpasswd "/etc/nginx/htpassword" do
user "foo"
password "bar"
end
我在Chef cookbook中看到了这种代码风格。 我对ruby很新,就像超级新手一样,但在其他语言方面有很多经验。
我想我已经知道htpasswd是一个过程?但令我感到困惑的是如何使用文件名,以及作业的工作方式user "foo"
答案 0 :(得分:1)
这是相同语法的最小实现,非常典型的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