1
votes

I have the following my_script.ruby

require 'erb'
require 'ostruct'
namespace = OpenStruct.new(:jmx_port => 9200, :markets=> ['CH', 'FR'])
template = File.open("my.json.erb", "rb").read;
puts ERB.new(template).result(namespace.instance_eval { binding })

and my.json.erb:

{
  "servers" : [ {
    "port" : "<%= jmx_port %>",
    "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
  } ]
}

but executing the script by irb my_script.ruby I get this error:

?> puts ERB.new(template).result(namespace.instance_eval { binding })
SyntaxError: compile error
(erb):10: syntax error, unexpected ';'
;  @markets.each do |market| -; _erbout.concat "\n      "

                           ^

for context, my.json.erb file is a puppet file, and using my_script.ruby I am trying to verify that the file is correct, before sending it to puppet.

what am I doing wrong?

ps: here it is the erb template, used by puppet: http://docs.puppetlabs.com/guides/templating.html

1

1 Answers

2
votes

There are a couple of issues with your erb:

  • You should use <% %> instead of <% -%> for things you don't want to output.
  • Since you're using an OpenStruct, you should use markets instead of @markets

Here's the final version of the my.json.erb file working:

{
  "servers" : [ {
    "port" : "<%= jmx_port %>",
    "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
  } ]
}