1

我正在尝试为 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

任何帮助深表感谢。

4

2 回答 2

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% 的内容对我来说是有意义的,但我将代码修改为以下内容并且它可以工作:

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
于 2015-07-13T00:28:22.673 回答
0

您通常必须将方法放在 () 中的“#{}”中
示例:

"#{method}"        # does not work
"#{(method)}"      # works
a = method; "#{a}" # works too
于 2015-07-13T05:15:53.293 回答