2

By default, when an an Erubis template raises an error, you get something like this:

(erubis):32:in `evaluate': compile error (SyntaxError)
(erubis):30: syntax error, unexpected ')', expecting ']'
(erubis):32: unterminated string meets end of file

The line numbers refer to the template.

That's all well and good when you just have one template, but I'm batch-processing a bunch of template files. What's the best way to replace the above with a more usable error message, e.g. one that shows the path to the source file instead of (erubis):32?

I'd thought of rescuing, messing around with the exception object, and raising again, but I'm wondering if there's an easier way provided by the Erubis API (or some other one).

rlkw1024
  • 6,455
  • 1
  • 36
  • 65

2 Answers2

2

You can pass :filename parameter to Erubis.

eruby = Erubis::Eruby.new(string, :filename=>"file.rhtml")
kwatch
  • 508
  • 1
  • 5
  • 12
  • Note that the "filename" can be anything you want. Eg I'm working with a system that has some Erb templates in the database. In a case like that, you can make the filename "templates_table_row_#{row.id}" or whatever seems helpful. The stacktrace might show "RuntimeError: esplosion! \ntemplates_table_row_5:2" – Nathan Long Aug 24 '15 at 19:54
0

I still suspect there might be a better way to do this using the Erubis API, but here's some code I wrote that seems to work:

def compile_template(template_path, template_str, context, &block)
  begin
    Erubis::Eruby.new(template_str).evaluate(context, &block)
  rescue Exception => exc
    trace_normalizer = lambda { |line| line.gsub(/^\(erubis\):/, template_path + ':') }
    backtrace = exc.backtrace.collect(&trace_normalizer)
    message = trace_normalizer.call(exc.message)
    raise exc.class, message, backtrace
  end
end
rlkw1024
  • 6,455
  • 1
  • 36
  • 65