instiki/vendor/rails/actionpack/lib/action_view/template_error.rb

99 lines
2.6 KiB
Ruby
Raw Normal View History

2007-01-22 14:43:50 +01:00
module ActionView
# The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a
# bunch of intimate details and uses it to report a very precise exception message.
class TemplateError < ActionViewError #:nodoc:
SOURCE_CODE_RADIUS = 3
attr_reader :original_exception
def initialize(template, assigns, original_exception)
@template, @assigns, @original_exception = template, assigns.dup, original_exception
@backtrace = compute_backtrace
2007-01-22 14:43:50 +01:00
end
def file_name
@template.relative_path
end
2007-01-22 14:43:50 +01:00
def message
ActiveSupport::Deprecation.silence { original_exception.message }
end
def clean_backtrace
if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
Rails.backtrace_cleaner.clean(original_exception.backtrace)
else
original_exception.backtrace
end
2007-01-22 14:43:50 +01:00
end
2007-01-22 14:43:50 +01:00
def sub_template_message
if @sub_templates
"Trace of template inclusion: " +
@sub_templates.collect { |template| template.relative_path }.join(", ")
2007-01-22 14:43:50 +01:00
else
""
end
end
def source_extract(indentation = 0)
return unless num = line_number
num = num.to_i
source_code = @template.source.split("\n")
start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
indent = ' ' * indentation
2007-01-22 14:43:50 +01:00
line_counter = start_on_line
return unless source_code = source_code[start_on_line..end_on_line]
source_code.sum do |line|
2007-01-22 14:43:50 +01:00
line_counter += 1
"#{indent}#{line_counter}: #{line}\n"
2007-01-22 14:43:50 +01:00
end
end
def sub_template_of(template_path)
2007-01-22 14:43:50 +01:00
@sub_templates ||= []
@sub_templates << template_path
2007-01-22 14:43:50 +01:00
end
2007-01-22 14:43:50 +01:00
def line_number
@line_number ||=
if file_name
regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
$1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
2007-01-22 14:43:50 +01:00
end
end
2007-01-22 14:43:50 +01:00
def to_s
"\n#{self.class} (#{message}) #{source_location}:\n" +
"#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
2007-01-22 14:43:50 +01:00
end
# don't do anything nontrivial here. Any raised exception from here becomes fatal
# (and can't be rescued).
2007-01-22 14:43:50 +01:00
def backtrace
@backtrace
2007-01-22 14:43:50 +01:00
end
private
def compute_backtrace
[
"#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
clean_backtrace.join("\n ")
]
end
def source_location
if line_number
"on line ##{line_number} of "
else
'in '
end + file_name
2007-01-22 14:43:50 +01:00
end
end
end