![](/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.