Capistrano 获取块

Capistrano fetch with block

块参数在 Capistrano 获取函数中的含义是什么?

fetch(:release_path) { current_path }

也可以默认调用吗?

fetch(:release_path, 'default') { current_path }

块和第二个参数都用于提供默认值。

例如:

# If :some_var is not set, then the default is used

fetch(:some_var) { "default" }
=> "default"

fetch(:some_var, "default")
=> "default"

# Once :some_var is set, the defaults are ignored

set(:some_var, "value")

fetch(:some_var) { "default" }
=> "value"

fetch(:some_var, "default")
=> "value"

永远不要同时指定第二个参数和块。在这种情况下,参数将被忽略并使用块。

# Don't do this, it is confusing
fetch(:another_var, "arg_default") { "block_default" }
=> "block_default"

选择一种形式而不是另一种形式的原因取决于默认值的类型。如果默认值为 hard-coded(如上例中的文字字符串),则参数形式有意义。另一方面,如果默认值是计算值(即方法调用),那么最好使用块。

Capistrano 的 fetch 的 default-value 行为模仿 Ruby 的 built-in Hash#fetch 的行为,记录在此处:http://ruby-doc.org/core-2.4.0/Hash.html#method-i-fetch