Class: Test::CodeSnippet

Inherits:
Object
  • Object
show all
Defined in:
lib/rubytest/code_snippet.rb

Overview

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, line) ⇒ CodeSnippet

Returns a new instance of CodeSnippet.



26
27
28
29
30
# File 'lib/rubytest/code_snippet.rb', line 26

def initialize(file, line)
  @file = file
  @line = (line || 1).to_i
  @code = CodeSnippet.cache(file)
end

Instance Attribute Details

#codeObject (readonly) Also known as: source

Returns the value of attribute code.



39
40
41
# File 'lib/rubytest/code_snippet.rb', line 39

def code
  @code
end

#fileObject (readonly)

Returns the value of attribute file.



33
34
35
# File 'lib/rubytest/code_snippet.rb', line 33

def file
  @file
end

#lineObject (readonly)

Returns the value of attribute line.



36
37
38
# File 'lib/rubytest/code_snippet.rb', line 36

def line
  @line
end

Class Method Details

.cache(file) ⇒ Object



7
8
9
10
# 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) ⇒ Object



13
14
15
16
17
# 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) ⇒ Object



20
21
22
23
# File 'lib/rubytest/code_snippet.rb', line 20

def self.from_error(exception)
  backtrace = exception.backtrace
  from_backtrace(backtrace)
end

Instance Method Details

#succObject



80
81
82
# File 'lib/rubytest/code_snippet.rb', line 80

def succ
  line += 1
end

#to_a(radius = 2) ⇒ Object



62
63
64
65
66
67
# 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) ⇒ Object



70
71
72
73
74
75
76
77
# 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) ⇒ Object

– TODO: ensure proper alignment by zero-padding line numbers ++



53
54
55
56
57
58
59
# 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_strObject



45
46
47
# File 'lib/rubytest/code_snippet.rb', line 45

def to_str
  code[line-1].strip
end