我有以下 puppet 示例模板:
{
"servers" : [ {
"port" : 9200,
"host" : "localhost",
"queries" : [
<% @markets.each do |market| -%>
{
"outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ],
"obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache",
"attr" : [ "hits","hitratio" ]
},
<% end -%>
],
"numQueryThreads" : 2
} ],
}
将它与 market=['UK','FR','IT'] 一起应用,我得到以下结果:
{
"servers" : [ {
"port" : 9200,
"host" : "localhost",
"queries" : [
{
"outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ],
"obj" : "solr/market_UK:type=queryResultCache,id=org.apache.solr.search.LRUCache",
"attr" : [ "hits","hitratio" ]
},
{
"outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ],
"obj" : "solr/market_FR:type=queryResultCache,id=org.apache.solr.search.LRUCache",
"attr" : [ "hits","hitratio" ]
},
{
"outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ],
"obj" : "solr/market_IT:type=queryResultCache,id=org.apache.solr.search.LRUCache",
"attr" : [ "hits","hitratio" ]
},
],
"numQueryThreads" : 2
} ],
}
问题是最后一个逗号,这使它成为无效的 solr 配置。
我可以使用 market.map 和 join(',') 而不是应用 markets.each do。 但是在这种情况下如何使用 map 呢?
我可以按如下方式使用 map :
<%= @markets.map{ |market| "hello_"+market }.join(',') -%>
这将打印 hello_UK,hello_FR,hello_IT
(注意我们在 hello_IT 之后没有逗号),
但我需要这样的东西:
{
"servers" : [ {
"port" : 9200,
"host" : "localhost",
"queries" : [
<% @markets.map |market| -%>
{
"outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ],
"obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache",
"attr" : [ "hits","hitratio" ]
},
<% }.join(',') -%>
],
"numQueryThreads" : 2
} ],
}
这行不通。
那么,如何让它发挥作用呢? 或者如何修改我的 puppet 模板以删除最后一个逗号?
最佳答案
这实际上是一个 Ruby 问题而不是 Puppet 问题。由于这是一个数组,只需将 .each
更改为 .each_with_index
。然后,您可以将最后一个逗号包裹在检查中,以查看当前索引值是否比索引大小小 1。例如,以下代码仅在当前 market
不是数组中的最后一个时才添加逗号:
<% @markets.each_with_index do |market, i| -%>
然后
}<%= ',' if i < (@markets.size - 1) %>
关于ruby - puppet 模板删除最后一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205915/