Class: Bullhorn::Backtrace

Inherits:
Object
  • Object
show all
Defined in:
lib/bullhorn/backtrace.rb

Instance Method Summary collapse

Constructor Details

#initialize(exception, options = {}) ⇒ Backtrace

Returns a new instance of Backtrace.



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/bullhorn/backtrace.rb', line 3

def initialize(exception, options = {})
  @exception = exception
  @raw       = exception.backtrace # Array
  @options   = { :context => true }

  @options.merge!(options)
  
  # Sample:
  # [ "(irb):3:in `irb_binding'",
  #   "/Users/rsc/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/irb/workspace.rb:80:in `eval'",
  #   "/Users/rsc/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/irb.rb:159:in `block (2 levels) in eval_input'",
end

Instance Method Details

#get_context(fname, line, size = 2) ⇒ Object

Returns nil or an array.



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bullhorn/backtrace.rb', line 17

def get_context(fname, line, size = 2)
  begin
    line = line.to_i
    from = [0, (line-size-1)].max
    lines = File.open(fname, 'r') { |file| file.lines.to_a[from...(line+size)] }

    i = [line - size, 0].max
    lines.map { |hash| i += 1; { (i-1) => hash } }
  rescue
    nil
  end
end

#to_aObject



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bullhorn/backtrace.rb', line 30

def to_a
  @raw.inject([]) do |arr, line|
    m = line.match(/^(?<file>[^:]+):(?<line>[0-9]+):in `(?<function>.*)'$/)

    arr << { :function => m[:function],
      :file     => m[:file],
      :line     => m[:line],
      :context  => (@options[:context] ? get_context(m[:file], m[:line]) : nil)
    }
    arr
  end
end

#to_jsonObject



43
44
45
# File 'lib/bullhorn/backtrace.rb', line 43

def to_json
  to_a.send(:to_json)
end