4 # This class extracts code snippets by looking at the backtrace of the passed error
5 class SnippetExtractor #:nodoc:
6 class NullConverter; def convert(code, pre); code; end; end #:nodoc:
7 begin; require 'rubygems'; require 'syntax/convertors/html'; @@converter = Syntax::Convertors::HTML.for_syntax "ruby"; rescue LoadError => e; @@converter = NullConverter.new; end
10 raw_code, line = snippet_for(error.backtrace[0])
11 highlighted = @@converter.convert(raw_code, false)
12 highlighted << "\n<span class=\"comment\"># gem install syntax to get syntax highlighting</span>" if @@converter.is_a?(NullConverter)
13 post_process(highlighted, line)
16 def snippet_for(error_line)
17 if error_line =~ /(.*):(\d+)/
20 [lines_around(file, line), line]
22 ["# Couldn't get snippet for #{error_line}", 1]
26 def lines_around(file, line)
28 lines = File.open(file).read.split("\n")
30 max = [line+1, lines.length-1].min
32 selected_lines.join("\n")
33 lines[min..max].join("\n")
35 "# Couldn't get snippet for #{file}"
39 def post_process(highlighted, offending_line)
41 highlighted.split("\n").each_with_index do |line, i|
42 new_line = "<span class=\"linenum\">#{offending_line+i-2}</span>#{line}"
43 new_line = "<span class=\"offending\">#{new_line}</span>" if i == 2