从Json变量生成模板

时间:2016-05-22 07:06:20

标签: ruby json loops hash erb

我想为一些本地微服务(存储在json文件中的变量)生成一些zabbix模板,请参阅下面的代码:

def self.haproxyTemplates
  file = File.read('./services.json')
  data_hash = JSON.parse(file)

  service = data_hash.keys
  service.each do |microservice|
  puts "Microservice: #{microservice}"
  httpport = data_hash["#{microservice}"]['httpport']
  puts "httpPort: #{httpport}"
  end

  open("./haproxy.xml", 'w+') { |f| f.chmod(0755)
  template=IO.read('./haproxyhealth.xml.erb')
  x = ERB.new(template).result(binding)
  f << "#{x}\n"
  }
end

这是我的services.json文件:

{
 "microservice1":{
  ....... ,
  "httpport": "27200"
   },
   "microservice2":{
   ......,
   "httpport": "25201"
   }
}

基本上在这种方法中,当我为每个微服务进行循环时,它成功运行直到它结束循环。当它创建haproxy.xml时,它会显示 &#34;未定义的局部变量或方法`httpport&#39; for main:Object(NameError)&#34; 我试图将httpport变量放在循环之外,它显示相同的错误。

请同时查看erb文件的一部分(如果我将&lt;%= httpport%&gt;替换为25201,则该文件是核心生成的):

 <items><% service.each do |microservice| %>
            <item>
                <name>haproxy <%= microservice %> - <%= httpport %></name>
 ......
 </item><% end %>   

1 个答案:

答案 0 :(得分:1)

这是一个工作示例,如果您将其粘贴到&#34; .rb&#34;文件,然后你可以运行它。

您的版本出现问题:binding不包含httport(即使它包含它,它对所有微服务都是一样的,因为它不会被重新分配。):解决方案:访问模板中的JSON(ruby哈希)数据,然后从那里循环。

require 'erb'

# data = parse JSON from file, inline here as example

data = {
  'microservice1' => {
    'httpport' => '27200'
  },
  'microservice2' => {
    'httpport' => '27201'
  }
}

open("haproxy.xml", 'w+') do |file|
  template = ERB.new(DATA.read)
  file << template.result(binding)
  file << "\n"
end


__END__
<items>
  <% data.each do |name, info| %>
    <item>
      <name>haproxy <%= name %> - <%= info['httpport'] %></name>
    </item>
  <% end %>
</items>