如何在厨师中使用另一本烹饪书中的图书馆方法? [英] How to use Library Methods from another cookbook in chef?

查看:3
本文介绍了如何在厨师中使用另一本烹饪书中的图书馆方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过这样的情况:我必须使用另一本食谱中的库函数,但我总是得到had an error: NoMethodError: undefined method 'func'

我尝试了什么:

Cookbook_1/Library/lib1.rb:

module namespace_1
  module namespace_2
    def func(var)
       something
    end
  end
end


Chef::Recipe.include(namespace_1::namespace_2)

Cookbook_2/metadata.rb:

.
.
depends 'cookbook_1'

Cookbook_2/resource/ome_resource.rb:

# Try 1
action :setup do
  a = func('abc')
end

#Try 2
extend namespace_1::namespace_2
action :setup do
  a = func('abc')
end


#Try 3
::Chef::Recipe.send(:include, namespace_1::namespace_2)
action :setup do
  a = func('abc')
end


#Try 4
action :setup do
  a = namespace_1::namespace_2::func('abc')
end


#Try 5
Chef::Recipe.include(namespace_1::namespace_2)
action :setup do
  a = namespace_1::namespace_2::func('abc')
end

我收到相同的错误,即NoMethodError: undefined method 'func' 我如何解决此问题?

推荐答案

要使在库或自定义资源中编写的Ruby方法在自定义资源操作中可用,我们应该使用action_class块。

引用自documentation

使用action_class块可使方法可用于自定义资源中的操作。

因此,在您的cookbook1中,除了拥有库之外,您还应该拥有action_class的自定义资源。我在你的基础上给出了我自己的例子。

Cookbook 1libraries/lib1.rb

# a custom function to just return the received argument 

module Namespace1
  module Namespace2  
    def custom_func(arg1)
      arg1
    end
  end
end

Cookbook 1resources/some_resource.rb

property :msg, String, name_property: true

# this is required to make sure functions are available to custom actions
action_class do
  include Namespace1::Namespace2
end

action :setup do
  a = custom_func(new_resource.msg)
  
  log a do
    level :info
  end
end

请注意,我在与库相同的食谱中创建了定制资源。现在可以在cookbook2中使用此自定义资源:

Cookbook 2metadata.rb

depends 'cookbook1'

Cookbook 2recipes/default.rb

cookbook1_some_resource 'Test custom function'

这篇关于如何在厨师中使用另一本烹饪书中的图书馆方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆