【问题标题】:Private method in custom resource does not work自定义资源中的私有方法不起作用
【发布时间】:2016-11-16 08:06:52
【问题描述】:

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

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

【问题讨论】:

    标签: chef-infra lwrp


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢,真的很难看。在普通的 LWRP 中,它是常规的方法调用。
      • 在普通 LWRP 中是一样的,但请记住,您是在资源类上定义方法,而不是在提供者上。
      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 2018-01-28
      • 1970-01-01
      • 2015-12-03
      • 2015-05-20
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多