使用ruby块初始化chef属性?

时间:2015-04-10 18:00:08

标签: ruby variables attributes chef

这是我要保存Time.now.strftime('%m%d%Y_%H%M')的输出的ruby命令我以为我可以在我的食谱中添加这样的东西'

TODAY={ ::Time.now.strftime('%m%d%Y_%H%M') }

但这似乎不起作用

==> default: [2015-04-10T17:53:44+00:00] ERROR: /tmp/vagrant-chef/eb36617d9c55f20fcee6cd316a379482/cookbooks/test-cookbook/recipes/install_app.rb:12: syntax error, unexpected '}', expecting tASSOC
    ==> default: TODAY={ (Time.now.strftime('%m%d%Y_%H%M')) }
    ==> default:                                             ^
    ==> default: [2015-04-10T17:53:44+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

最终我想把它变成一个属性,这样我就可以从多个食谱中访问它了

default['neustar-npac-deployment']['node_ohai_time'] = TODAY={ ::Time.now.strftime('%m%d%Y_%H%M') }

谢谢!

1 个答案:

答案 0 :(得分:2)

根据您的要求,我将此作为答案发布。

现在你正在使用{}错误,因为这不是一个块而是一个Hash字面值,这就是为什么它在抱怨。为了使其成为块,您必须使用lambdaProc对象。

<强>拉姆达

lambda可以使用2种不同语法样式之一

创建
-> { "This is a lambda" } 
#=> #<Proc:0x2a954c0@(irb):1 (lambda)>
lambda { "This is also a lambda" }
#=> #<Proc:0x27337c8@(irb):2 (lambda)>

无论哪种方式都是完全可以接受的

<强> PROC

可以使用Proc.new { "This is a proc" }

创建过程

对于这个问题,不需要语义差异。

lambdaProc将懒惰地评估#call上块内的语句,这意味着该值可以保持流畅。

让我们举个例子:

 NOW = Time.now.strftime('%m%d%Y_%H%M')
 # in this case NOW will be evaluated once and will always equal the 
 # string result of when it was first interpretted
 TODAY = -> {Time.now.strftime('%m%d%Y_%H%M')}
 # in this case TODAY is simply a lambda and it's value will be dependent
 # upon the time when you "call" it so something like this will clearly illustrate
 # the difference
 while NOW == TODAY.call
    puts "Still the same time" 
 end 
 # after this NOW will still reflect it's initial set value and for 
 # a while ~ 1 minute this will output "Still the same time" 
 # at some point TODAY.call will increment up by 1 minute because it is 
 # re-evaluated on each `#call` thus allowing it to change periodically with the clock

我希望这在某种程度上可以帮助您更好地理解这个概念。