【问题标题】:Chef library helper method is undefinedChef 库辅助方法未定义
【发布时间】:2015-12-25 23:42:12
【问题描述】:

我正在尝试编写一个基于条件的 LWRP,它将调用帮助程序库中的方法。我在让提供程序读取外部方法时遇到语法问题。

提供者非常简单

# 提供者/提供者.rb require_relative '../libraries/acx_shared' 包括Acx 行动:创建做 Chef::Log.debug('{jefflibrary->lwrp->user} - start') 如果@new_resource.shared == true Acx::User::Shared.true_shared() 别的 Acx::User::Shared.false_shared() 结尾 如果@new_resource.sudo == true Chef::Log.error('我有权力') 别的 Chef::Log.error('我的力量微弱无力') 结尾 如果@new_resource.password == true Chef::Log.error('密码是 12345') 别的 Chef::Log.error('我永远不会告诉你气闸的秘密') 结尾 Chef::Log.debug('{jefflibrary->lwrp->user} - end') 结尾

与辅助库一起

#libraries/acx_shared.rb 模块Acx 模块用户 模块共享 def true_shared #puts废话 Chef::Log.error('我是从图书馆参考资料中提取的') 结尾 def false_shared Chef::Log.error('我不太擅长分享') 结尾 结尾 结尾 结尾

但无论何时我尝试运行它,而不管资源属性设置如何,我都会不断得到

无方法错误 ------------- Acx::User::Shared:Module 的未定义方法“false_shared”

我显然在编写帮助程序库的文档中遗漏了一些内容,但我不确定是什么。尝试移动一些东西,但开始没有想法。

【问题讨论】:

  • acx_shared 是否通过要求拉入 helper_library?是不是拉了它?
  • helper_library 在技术上被命名为 acx_shared.rb,但我将其标记为 helper_library,因为我希望更容易理解。它应该是 provider.rb 使用 require 拉入帮助程序库并包含 Acx 模块。然而,它并没有引入任何方法。这是我缺少的语法。
  • 恕我直言,这并没有让它更容易理解。
  • 尝试删除 include Acx 可能发生的情况是,因为您正在这样做,它实际上是在 Acx 内部寻找另一个模块名称 Acx。所以要么删除包含或删除 Acx:: 从调用 *shared 方法

标签: ruby chef-infra lwrp


【解决方案1】:

尝试删除 include Acx

可能发生的情况是,因为您正在这样做,它实际上是在在 Acx 内部寻找另一个模块名称 Acx。 因此,要么从对 *shared 方法的调用中删除包含或删除 Acx::。 您也不能在尝试时直接从模块调用实例变量。您需要让一个类包含该模块,然后在该类的对象上调用该方法。
作为替代方案,您可以将方法提升为类方法(self.),然后直接调用它们。

类似:

# providers/provider.rb
require_relative '../libraries/acx_shared'

action :create  do
  Chef::Log.debug('{jefflibrary->lwrp->user} - start')

acx = Class.new.exted(Acx::User::Shared)
if @new_resource.shared == true
  acx.true_shared()
else
  acx.false_shared()
end

if @new_resource.sudo == true
  Chef::Log.error('I HAVE THE POWER')
else
  Chef::Log.error('my power is weak and feeble')
end
if @new_resource.password == true
  Chef::Log.error('the secret password is 12345')
else
  Chef::Log.error('I will never tell you the secret to the airlock')
end

  Chef::Log.debug('{jefflibrary->lwrp->user} - end')
end

#libraries/acx_shared.rb
module Acx
  module User
    module Shared
    def self.true_shared
      #puts blah
      Chef::Log.error('I am pulling this from a library reference')
    end
    def self.false_shared
      Chef::Log.error('I am not very good at sharing')
    end
  end
end
end

【讨论】:

  • 感谢您的跟进。不幸的是,我尝试了这两种方法,但仍然有可能发生的通常神秘的错误。 NoMethodError ------------- Acx::User::Shared:Class 的未定义方法 `true_shared'
  • 没错。你不能直接调用它,因为那是一个实例方法。如果你想直接调用它,你需要将模块包含到一个类中,你需要将它提升为一个类 var(前面的 self.)。代码示例已更新。
  • 工作得很好。当您调用包含时,诀窍肯定是在模块上结束。
猜你喜欢
  • 2011-11-19
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多