Class: PrettyFace::Formatter::ReportStep::SnippetExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/pretty_face/formatter/report.rb

Constant Summary collapse

@@converter =
Syntax::Convertors::HTML.for_syntax "ruby"

Instance Method Summary collapse

Instance Method Details

#file_name_and_line(error_line) ⇒ Object



235
236
237
238
239
240
241
# File 'lib/pretty_face/formatter/report.rb', line 235

def file_name_and_line(error_line)
  if error_line =~ /(.*):(\d+)/
    file = $1
    line = $2.to_i
    [file, line]
  end
end

#lines_around(file, line) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/pretty_face/formatter/report.rb', line 259

def lines_around(file, line)
  if File.file?(file)
    lines = File.open(file).read.split("\n")
    min = [0, line-3].max
    max = [line+1, lines.length-1].min
    selected_lines = []
    selected_lines.join("\n")
    lines[min..max].join("\n")
  else
    "# Couldn't get snippet for #{file}"
  end
end

#post_process(highlighted, offending_line) ⇒ Object



272
273
274
275
276
277
278
279
280
# File 'lib/pretty_face/formatter/report.rb', line 272

def post_process(highlighted, offending_line)
  new_lines = []
  highlighted.split("\n").each_with_index do |line, i|
    new_line = "<span class=\"linenum\">#{offending_line+i-2}</span>#{line}"
    new_line = "<span class=\"offending\">#{new_line}</span>" if i == 2
    new_lines << new_line
  end
  new_lines.join("\n")
end

#snippet(error) ⇒ Object



243
244
245
246
247
248
# File 'lib/pretty_face/formatter/report.rb', line 243

def snippet(error)
  raw_code, line, file = snippet_for(error[0])
  highlighted = @@converter.convert(raw_code, false)

  "<pre class=\"ruby\"><strong>#{file + "\n"}</strong><code>#{post_process(highlighted, line)}</code></pre>"
end

#snippet_for(error_line) ⇒ Object



250
251
252
253
254
255
256
257
# File 'lib/pretty_face/formatter/report.rb', line 250

def snippet_for(error_line)
    file, line = file_name_and_line(error_line)
  if file
    [lines_around(file, line), line, file]
  else
    ["# Couldn't get snippet for #{error_line}", 1]
  end
end