如何在食谱之间共享代码

How to share code between recipes

我有一个循环遍历属性中定义的一堆数据的方法:

node["repos"].each do |repo, data|
  ...do stuff...
end

...do stuff...部分相当长,我想在多个食谱中重复使用它,唯一的区别是属性中的数据集不同。

我尝试将循环内部移动到另一个食谱并像这样包含它:

node["repos"].each do |repo, data|
   include_recipe "other_recipe"
end

但是当它尝试 运行 other_recipe 时,data 变量不存在。

食谱之间共享代码的"proper"方式是什么?

不幸的是,这不起作用,因为 include_recipe 都不允许传递参数,并且 "debounced" 意味着它只对给定的配方运行一次。

目前对于这种事情最简单的选择是制作自定义资源。其他选项包括定义和辅助方法,但我会从自定义资源开始,然后从那里开始。东西块的输入(repodata 在这种情况下)成为资源属性,配方代码块进入资源的操作方法。

最简单的事情就是将此 do stuff 移至图书馆。

my_cookbook/libraries/myhelper.rb:

module Myhelper
  def do_stuff( repo, data )
    [...you can use all kinds of resources here as in recipe...]
  end
end

然后你可以像这样在食谱中使用这个模块:

another_cookbook/recipes/some_recipe.rb:

extend Myhelper
do_stuff( node[:attribute1], node[:attribute2] )

只需确保在元数据中添加对 my_cookbook 的依赖:

another_cookbook/metadata.rb:

depends 'my_cookbook'