自定义资源中的私有方法不起作用

时间:2015-12-10 22:16:29

标签: chef lwrp

我想使用自定义资源做类似的事情: 这是提供者代码(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 ...

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

new_resource.send(:my_private_method, a),并且由于这个原因使得私事不是非常推荐的。

相关问题