簡體   English   中英

Chef LWRP“ nil:NilClass的未定義方法'checkname'”

[英]Chef LWRP “undefined method 'checkname' for nil:NilClass”

我試圖寫一個廚師菜譜的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

任何幫助深表感謝。

所以我在#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

您通常必須將方法放在()的“#{}”中
例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM