ruby 检查 Chef 中是否存在嵌套属性的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18986096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct way to check for the existence of a nested attribute in Chef?
提问by borntyping
There are multiple ways to check for the existence of a nested attribute in chef, and I'm not sure which is correct/best, and if any will result in empty attributes being stored on the node:
有多种方法可以检查 Chef 中是否存在嵌套属性,我不确定哪个是正确/最好的,如果有的话会导致节点上存储空属性:
node[:parent] and node[:parent][:child]
node.attribute?(:parent) and node[:parent].attribute?(:child))
node[:parent].nil? and node[:parent][:child].nil?
It'd be greatly preferred to be able to check for the parent and child at the same time, but I don't know if that's possible. I am using Chef 10, not Chef 11, though answers explaining either are welcome.
最好能够同时检查父母和孩子,但我不知道这是否可能。我使用的是 Chef 10,而不是 Chef 11,尽管欢迎回答解释两者。
回答by shawmzhu
Node attribute object is HashMap. You can use ruby native API to lookup nested attributes.
节点属性对象是HashMap。您可以使用 ruby 本机 API 来查找嵌套属性。
Chef Node Object provides a number of helper methods like:
Chef 节点对象提供了许多辅助方法,例如:
node.attribute?()
node[:foo].attribute?(:bar)
node[:foo].member?(:bar)
There is also a new method node.debug_value()in chef 11 to help you debug node attributes which is also helpful:
node.debug_value()Chef 11 中还有一个新方法可以帮助您调试节点属性,这也很有帮助:
node.debug_value(:foo, :bar)
Details can be found from the article Chef 11 In-Depth: Attributes Changes
回答by borntyping
The way I've solved this more recently has been to always set default values for attributes used in a cookbook where possible.
我最近解决这个问题的方法是尽可能为食谱中使用的属性设置默认值。
For example, cookbook/attributes/default.rbwould contain:
例如,cookbook/attributes/default.rb将包含:
default[:parent][:child] = nil
And the in the recipe, any check for the attributes value can be reduced to:
在配方中,对属性值的任何检查都可以简化为:
node[:parent][:child].nil?
Of course, it's usually far more useful to have a usable default value and to not have to check at all.
当然,拥有一个可用的默认值并且根本不需要检查通常要有用得多。
回答by Jason Martin
Check out the chef-sugar cookbook deep_fetchextension that allows for safe references to deep attributes.
查看chef-sugar 食谱deep_fetch扩展,它允许安全引用深层属性。

