TyM*_*Mac 6 ruby chef-recipe rubocop
我有一个配方,其中包含以下代码,即lint测试失败:
service 'apache' do
supports :status => true, :restart => true, :reload => true
end
Run Code Online (Sandbox Code Playgroud)
它失败并出现错误:
Use the new Ruby 1.9 hash syntax.
supports :status => true, :restart => true, :reload => true
Run Code Online (Sandbox Code Playgroud)
不确定新语法是什么样的......有人可以帮忙吗?
Seb*_*lma 12
在Ruby版本1.9中引入了一种新的哈希文字语法,其键是符号.哈希使用"哈希火箭"运算符来分隔键和值:
a_hash = { :a_key => 'a_value' }
Run Code Online (Sandbox Code Playgroud)
在Ruby 1.9中,这种语法是有效的,但只要键是符号,它也可以写成:
a_hash = { a_key: 'a_value' }
Run Code Online (Sandbox Code Playgroud)
正如Ruby样式指南所说,当您的哈希键是符号时,您应该更喜欢使用Ruby 1.9哈希文字语法(请参阅参考资料):
# bad
hash = { :one => 1, :two => 2, :three => 3 }
# good
hash = { one: 1, two: 2, three: 3 }
Run Code Online (Sandbox Code Playgroud)
另外一个提示:不要将Ruby 1.9哈希语法与哈希火箭混合在同一个哈希文字中.如果你的键符号不符合哈希火箭的语法(参见参考资料):
# bad
{ a: 1, 'b' => 2 }
# good
{ :a => 1, 'b' => 2 }
Run Code Online (Sandbox Code Playgroud)
所以你可以尝试:
service 'apache' do
supports status: true, restart: true, reload: true
end
Run Code Online (Sandbox Code Playgroud)
如果你想看看Rubocop"方式"是什么,你可以在命令行中运行它,这将仅为HashSyntax警告或标志自动更正你的代码:
rubocop --only HashSyntax --auto-correct
Run Code Online (Sandbox Code Playgroud)