class Test::CodeSnippet

Thanks goes to Suraj N. Kurapati for the origins of this code.

Attributes

code[R]
file[R]
line[R]
source[R]

Public Class Methods

cache(file) click to toggle source
# File lib/rubytest/code_snippet.rb, line 7
def self.cache(file)
  @cache ||= {}
  @cache[file] ||=  File.exist?(file) ? File.readlines(file) : ['(N/A)']
end
from_backtrace(backtrace) click to toggle source
# File lib/rubytest/code_snippet.rb, line 13
def self.from_backtrace(backtrace)
  backtrace.first =~ /(.+?):(\d+(?=:|\z))/ or return nil
  file, line = $1, $2.to_i
  new(file, line)
end
from_error(exception) click to toggle source
# File lib/rubytest/code_snippet.rb, line 20
def self.from_error(exception)
  backtrace = exception.backtrace
  from_backtrace(backtrace)
end
new(file, line) click to toggle source
# File lib/rubytest/code_snippet.rb, line 26
def initialize(file, line)
  @file = file
  @line = (line || 1).to_i
  @code = CodeSnippet.cache(file)
end

Public Instance Methods

succ() click to toggle source
# File lib/rubytest/code_snippet.rb, line 80
def succ
  line += 1
end
to_a(radius=2) click to toggle source
# File lib/rubytest/code_snippet.rb, line 62
def to_a(radius=2)
  r = range(radius)
  r.map do |n|
    code[n-1].chomp
  end
end
to_omap(radius=2) click to toggle source
# File lib/rubytest/code_snippet.rb, line 70
def to_omap(radius=2)
  a = []
  r = range(radius)
  r.each do |n|
    a << {n => code[n-1].chomp}
  end
  a
end
to_s(radius=2) click to toggle source
# File lib/rubytest/code_snippet.rb, line 53
def to_s(radius=2)
  r = range(radius)
  f = " %2s %0#{r.last.to_s.length}d %s"
  r.map do |n|
    f % [('=>' if n == line), n, code[n-1].chomp]
  end.join("\n")
end
to_str() click to toggle source
# File lib/rubytest/code_snippet.rb, line 45
def to_str
  code[line-1].strip
end

Private Instance Methods

range(radius) click to toggle source
# File lib/rubytest/code_snippet.rb, line 87
def range(radius)
  [line - radius, 1].max..[line + radius, source.length].min
end