![](/img/trans.png)
[英]How to use a chef helper library from another chef cookbook in a ruby_block
[英]How to use Library Methods from another cookbook in chef?
我有一个案例,我必须使用另一个食谱中的库 function,但我总是遇到had an error: NoMethodError: undefined method 'func'
。
我尝试了什么:
食谱_1/库/lib1.rb:
module namespace_1
module namespace_2
def func(var)
something
end
end
end
Chef::Recipe.include(namespace_1::namespace_2)
食谱_2/metadata.rb:
.
.
depends 'cookbook_1'
食谱_2/resource/some_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
块。
引用文档:
使用
action_class
块使方法可用于自定义资源中的操作。
因此,在您的cookbook1
中,除了拥有库之外,您还应该拥有一个带有action_class
的自定义资源。 我根据你的例子给出我自己的例子。
食谱1: libraries/lib1.rb
:
# a custom function to just return the received argument
module Namespace1
module Namespace2
def custom_func(arg1)
arg1
end
end
end
食谱1: resources/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
中使用:
食谱2 : metadata.rb
.rb
depends 'cookbook1'
食谱2 : recipes/default.rb
:
cookbook1_some_resource 'Test custom function'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.