【问题标题】:Is attr_accessor required in resource definition of chef lwrp?厨师 lwrp 的资源定义中是否需要 attr_accessor?
【发布时间】:2015-04-24 21:23:23
【问题描述】:

我使用 chefdk 创建了一个 LWRP,并严格按照文档和一些博客文章进行操作。

资源

actions :install
default_action :install

provides :foo

attribute :name, :kind_of => String, :name_attribute => true

提供者

provides :foo

def whyrun_supported?
  true
end

use_inline_resources

action :install do
  converge_by("install: #{@new_resource}") do
    execute "installation of: #{@new_resource.name}" do
      command "foo install #{@new_resource.name}"
    end
  end
end

def load_current_resource
  @current_resource = Chef::Resource::Foo.new @new_resource.name
  @current_resource.name = @new_resource.name
end

在食谱中使用此 LWRP 时,我会收到以下错误:

undefined method `name=' for Chef::Resource::Foo

我可以修复它的唯一方法是将attr_accessor :name 添加到资源定义中。但我从未将其视为任何文档中的要求。从文档中,我假设 Chef 在资源/提供程序编译期间负责在任何属性上设置 attr_accessor。谁能确认我的发现或解释真正发生的事情?

谢谢。

【问题讨论】:

    标签: chef-infra lwrp


    【解决方案1】:
    def load_current_resource
      @current_resource = Chef::Resource::Foo.new @new_resource.name
      @current_resource.name = @new_resource.name
    end
    

    您的问题在这里,name 应该是不变的(用于匹配当前和新资源),因为它识别资源,您不应该尝试设置@current_resource.name

    去掉这一行,没有访问器应该没问题。

    【讨论】:

    • 我使用dougireton.com/blog/2013/01/07/creating-an-lwrp-part-2 作为指导。该博客文章显示使用称为“名称”的方法设置“名称”,以及以相同方式设置的其他属性。我只是假设 = 也可以。这位厨师是否使用“method_missing”为 attrs 创建方法?还是 Ruby 说 = 只能在使用 'attr_accessor' 的情况下工作?
    • 对不起,我只能回答我从厨师那里知道的,我不是红宝石专家,但据我所知,属性是用方法设置的(对名为 set_or_return 的方法的子调用)允许以两种方式使用它们(访问和分配)如果您对厨师的内部感兴趣,可以查看chef code on github
    • 阅读代码并执行一些测试后,我可以确认 Chef 正在为每个属性动态创建一个 setter/getter,并且应该调用这些方法来设置 load_current_resource 中的属性值.我不确定这是否说明了 Chef 认为是惯用代码的任何内容,但他们并没有规定对属性使用读取器和写入器。
    • @glevine 很高兴它有帮助,irc.freeware.net 上有 #chef 频道和一个邮件列表,如果你想深入了解这个主题,厨师开发人员会回答和交谈(请参阅标签 wiki 获取链接)
    • irc 上一条评论是 irc.freenode.net :/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多