下面是相同语法的最小实现,这是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