我想创建一个Chef库:
该库旨在与外部系统连接并从那里检索一些输入.我需要访问节点属性以允许用户覆盖从外部系统接收的输入:
inputs = MyLib.get_inputs
Run Code Online (Sandbox Code Playgroud)
这是受那些文档的启发.
class Chef::Recipe::MyLib
def self.get_inputs
override_inputs = node.fetch(:mylib, Hash.new).fetch(:override_inputs, nil)
unless override_inputs.nil?
return override_inputs
end
# Do stuff and return inputs (no problem here)
# ...
end
end
Run Code Online (Sandbox Code Playgroud)
现在我得到:
undefined local variable or method `node' for Chef::Recipe::Scalr:Class
Run Code Online (Sandbox Code Playgroud)
set*_*rgo 18
除非将其传递给初始化程序,否则您无权访问库中的节点对象:
class MyHelper
def self.get_inputs_for(node)
# Your code will work fine
end
end
Run Code Online (Sandbox Code Playgroud)
然后你用它来调用它:
inputs = MyHelper.get_inputs_for(node)
Run Code Online (Sandbox Code Playgroud)
或者,您可以创建一个模块并将其混合到Chef Recipe DSL中:
module MyHelper
def get_inputs
# Same code, but you'll get "node" since this is a mixin
end
end
Chef::Recipe.send(:include, MyHelper)
Run Code Online (Sandbox Code Playgroud)
然后您可以访问get_inputs配方中的方法:
inputs = get_inputs
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个实例方法与类方法.
简而言之,node除非作为参数给出,否则库不能访问该对象.如果它们混合到Recipe DSL中,模块将会.此外,该node对象实际上是一个实例变量,因此它在类级别(即self.)不可用.
| 归档时间: |
|
| 查看次数: |
9511 次 |
| 最近记录: |