厨师LWRP“未定义的方法'检查名称为零:NilClass”

问题描述:

我想写一个厨师食谱的LWRP,我遇到了一个奇怪的问题,这个属性似乎是完全有效的一行,并且接下来是nil厨师LWRP“未定义的方法'检查名称为零:NilClass”

从供应商代码,错误的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 

任何帮助深表感谢。

+0

很难判断'get_check_filename(@ current_resource.checkname)'可能会在没有看到整个提供者的情况下做什么。诺亚的权利,但你应该'current_resource',而不是'@ current_resource'。 – Martin

所以我就在#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和厨师走了,那是有道理所以只喜欢20%至,但我修改我的代码到下方,它的工作原理:

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 

通常你需要把方法 “#{}” 中的()
例子:

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