【问题标题】:Chef LWRP "undefined method 'checkname' for nil:NilClass"厨师 LWRP “nil:NilClass 的未定义方法 'checkname'”
【发布时间】:2015-07-13 13:15:53
【问题描述】:

我正在尝试为 Chef 食谱编写 LWRP,但遇到了一个奇怪的问题,即该属性在一行上似乎完全有效,而 nil 在下一行。

从提供程序代码中,source 行出错:

def create_check
  cookbook_file get_check_filename(@current_resource.checkname) do
    source  "checks/#{@current_resource.checkname}" # undefined method `checkname' for nil:NilClass
    mode    '0644'
    action  :create
  end
end

load_current_resource 方法只是为了表明它初始化:

def load_current_resource
  @current_resource = Chef::Resource::OmdCheck.new(@new_resource_name)
  @current_resource.checkname(@new_resource.checkname) # right here!
  @current_resource.sitename(@new_resource.sitename)
  @current_resource.sitecfgroot(sprintf(CMK_CFGROOT_FRM, @new_resource.sitename))
  @current_resource.perfometer(@new_resource.perfometer)
  @current_resource.pnptemplate(@new_resource.pnptemplate)

  @current_resource.exists = check_exists?(@current_resource.checkname)
end

非常感谢任何帮助。

【问题讨论】:

  • 如果没有看到整个提供商,很难判断get_check_filename(@current_resource.checkname) 可能会做什么。不过诺亚是对的,你应该是current_resource,而不是@current_resource

标签: ruby chef-infra lwrp


【解决方案1】:

所以我在#chef 上得到了答案:

<@coderanger> Sammitch: Use current_resource, not @current_resource
< Sammitch> it's passed in as an instance var?
<@coderanger> Sammitch: No, its actually a method on Provider
<@coderanger> as is new_resource
<@coderanger> the issue is that the block on a resource is evaluated against the resource object
<@coderanger> So in there, @foo is looking at an ivar on the new resource object
<@coderanger> _but_ there is some magic
<@coderanger> Chef::Resource has a method_missing to forward unknown method calls to the enclosing provider
<@coderanger> So #current_resource gets forwarded up for you
<@coderanger> Basically never use the ivar form
<@coderanger> Always new_resource and current_resource instead
<@coderanger> and it will mostly JFW

就 Ruby 和 Chef 而言,我还很年轻,所以只有 20% 的内容对 有意义,但我将代码修改为以下内容并且它可以工作: p>

def create_check
  cookbook_file get_check_filename(@current_resource.checkname) do
    source  "checks/#{current_resource.checkname}" # removed the @
    mode    '0644'
    action  :create
  end
end

【讨论】:

    【解决方案2】:

    你通常必须把方法放在"#{}" in ()
    示例:

    "#{method}"        # does not work
    "#{(method)}"      # works
    a = method; "#{a}" # works too
    

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多