4

在一本食谱中,我有一个库(client_helper.rb)。在其中定义了一个模块。模块名称是Client_helper。这是模块代码。

module Client_helper
# This module contains helper methods

def network_zone
        Chef::Log.debug('network zone called...********')
        Chef::Log.debug("inside-::::"+self.class.to_s)
end    

end
Chef::Recipe.send(:include, Client_helper)

现在我有默认食谱。我从直接配方调用方法network_zone的地方它正在工作。

但是,当我在ruby​​_block(例如 Client_helper.network_zone)中调用方法 network_zone 时,它​​不起作用

请找到食谱代码。

# Cookbook: client
# Recipe: default

Chef::Resource.send(:include, Sap_splunk_client_helper)   


  host_network_zone = network_zone # This is working

Log.info("inside-::::"+self.class.to_s)

ruby_block 'parse auto generated templates' do
  block do
    host_network_zone = Client_helper.network_zone #This is not working
    Log.info("inside ruby block-::::"+self.class.to_s)
end
end

我的食谱目录结构-

在此处输入图像描述

请帮我。

4

2 回答 2

7

无需将方法注入任何提供程序类,最好只将其注入您需要的类:

Chef::Recipe.send(:include, Client_helper)
Chef::Resource::RubyBlock.send(:include, Client_helper)

通过注入方法,您正在对这些类进行修补,这会带来与“猴子修补”相关的所有风险(谷歌搜索可能具有教育意义)。

如果您将 #network_zone 助手注入 Chef::Provider 和 Chef::Resource 基类,这将覆盖任何核心资源或提供者,或任何食谱资源或提供者中任何类似命名的方法。如果其他人使用该名称的方法,您将破坏他们的代码。

于 2016-05-26T22:51:51.730 回答
1

找到了解决办法!!您需要在 Chef::Recipe、Chef::Resource 和 Chef::Provider 中包含模块。所以完整的代码将是 -

# This module contains helper methods
module Client_helper     

def network_zone
        Chef::Log.debug('network zone called...********')
        Chef::Log.debug("inside-::::"+self.class.to_s)
end    

end
Chef::Recipe.send(:include, Client_helper)
Chef::Resource.send(:include, Client_helper)
Chef::Provider.send(:include, Client_helper) 

我希望这有帮助。

于 2016-05-25T13:08:53.180 回答