0

I need to evaluate an ERB template, and then ensure it's a valid NGINX configuration file, but vanilla ERB doesn't allow the -%> directive. How am I able to add that extension into my rakefile?

I've been able to replicate the problem in irb as so:

~ $ irb
irb(main):001:0> require 'erb'
=> true
irb(main):002:0> var = "yeah"
=> "yeah"
irb(main):003:0> ERB.new(" <% if var == 'yeh' -%>
irb(main):004:1"    something
irb(main):005:1"    <% else -%>
irb(main):006:1"    something else
irb(main):007:1"    <% end -%>
irb(main):008:1" ").result binding #"
SyntaxError: (erb):1: syntax error, unexpected ';'
...concat " ";  if var == 'yeh' -; _erbout.concat "\nsomething\...
...                               ^
(erb):3: syntax error, unexpected keyword_else, expecting $end
;  else -; _erbout.concat "\nsomething else\n"
       ^
    from /usr/lib/ruby/1.9.1/erb.rb:838:in `eval'
    from /usr/lib/ruby/1.9.1/erb.rb:838:in `result'
    from (irb):3
    from /usr/bin/irb:12:in `<main>'
Jacklynn
  • 1,503
  • 1
  • 13
  • 23

1 Answers1

4

In order to use the -%> syntax in ERB you need to set the trim mode option to '-'. This is the third option to the constructor, you will need to pass nil as the second (unless you want to change the safe_level from the default):

ERB.new(" <% if var == 'yeh' %>
    something
    <% else %>
    something else
    <% end %>
 ", nil, '-').result binding

Without this option the - is included in the generated Ruby script and gives you the syntax error when you try to run it.

Note that there is another eRuby processor, Erubis which might have slightly different options (it can still use this syntax). This one is used by Rails. Check out the docs for more info.

matt
  • 78,533
  • 8
  • 163
  • 197
  • Heh. Thanks for providing clarification. Apparently it *is* in standard ERB now. This is funny. – Dave Newton Jun 01 '15 at 17:05
  • @DaveNewton looking at the docs, it seems it was added in Ruby 2.0. I guess people coming from Rails expected it so it was added. – matt Jun 01 '15 at 17:08
  • Makes sense. I didn't think it used to be in ERB proper, but it's good to have actual facts. – Dave Newton Jun 01 '15 at 17:08
  • @DaveNewton it looks like it was just the docs added in 2.0: https://github.com/ruby/ruby/commit/4fa9e3307dd3b2cf3afea278a833a5d05ddb45de, the trim option goes back even earlier, to 1.8 I think: https://github.com/ruby/ruby/commit/f8817c7262afd77028e7cb704e440b67a1104cb7 – matt Jun 01 '15 at 20:09
  • Oh, I had no idea--I think my original rememberings are either wrong, or from a pretty old version. – Dave Newton Jun 01 '15 at 20:12