1

我想使用自定义资源做类似的事情:这是有效的提供程序代码(LWRP)

action :create
  my_private_method(a)
  my_private_method(b)
end

private
def my_private_method(p)
  (some code)
end

如果我使用自定义资源制作类似的代码,并定义私有方法,则 chef-client 运行失败并出现错误:

No resource or method 'my_private_method' for 'LWRP resource ...

在自定义资源中声明/调用私有方法的语法是什么?

4

2 回答 2

3

更新:这是现在的首选方式:

action :create do
  my_action_helper
end

action_class do
  def my_action_helper
  end
end

这些替代方案都有效:

action :create do
  my_action_helper
end

action_class.class_eval do
  def my_action_helper
  end
end

和:

action :create do
  my_action_helper
end

action_class.send(:define_method, :my_action_helper) do
end

在后一种情况下,如果您的方法上有 args 或块,则它是标准的 define_method 语法,示例:

# two args
action_class.send(:define_method, :my_action_helper) do |arg1, arg2|
# varargs and block
action_class.send(:define_method, :my_action_helper) do |*args, &block|

我们可能需要将一些 DSL 糖添加到自定义资源 API 中以使其更好。

(为此问题添加票证:https ://github.com/chef/chef/issues/4292 )

于 2015-12-11T22:24:54.647 回答
0

new_resource.send(:my_private_method, a),因此不强烈建议将事情设为私有。

于 2015-12-10T22:57:39.837 回答