Class | HelpfulERB |
In: |
lib/helpful_erb.rb
|
Parent: | Object |
erb | [RW] | ERB object |
filename | [RW] | Template filename |
lines_after | [RW] | |
lines_before | [RW] |
Instantiate a new object with ERB text content. For displaying exception backtrace, also specify the filename the ERB content was read from.
Options:
# File lib/helpful_erb.rb, line 26 def initialize(text, filename=nil, opts={}) @text = text @filename = filename @lines_before = opts[:before] || 5 @lines_after = opts[:after] || 1 @erb = ::ERB.new(@text, nil, '-') @erb.filename = @filename if @filename end
Return the rendered string produced from the ERB template. Optionally provide the binding context to use. If an exception is caught when rendering the template, raise a HelpfulERB::Error.
# File lib/helpful_erb.rb, line 39 def result(binder=nil) begin return @erb.result(binder) rescue Exception => e # Extract filename and line number of exception. stack = caller 0 line_number = nil template = @filename for frame in e.backtrace if frame =~ /^([^:]+):(\d+):in `(render|result)'$/ or frame =~ /^(#{@filename}):(\d+):in / template = $1 line_number = $2.to_i break end end unless line_number raise Exception.new("Caught ERB error but couldn't find line number in backtrace:\n#{e.backtrace.join("\n")}") end lines = @text.split(/\n/) min = line_number - @lines_before min = 0 if min < 0 max = line_number + @lines_after max = lines.size if max > lines.size width = max.to_s.size msg = "Problem with template '#{template}' at line #{line_number}:\n" for i in min..max n = i+1 marker = n == line_number ? "*" : "" msg << "\n%2s %#{width}i %s" % [marker, n, lines[i]] end msg << "\n\n(#{e.exception.class}) #{e.message}" raise HelpfulERB::Error.new(msg, e) end end