class Pry::Command::Wtf

Constants

RUBY_FRAME_PATTERN

Public Instance Methods

options(opt) click to toggle source
# File lib/pry/commands/wtf.rb, line 27
def options(opt)
  opt.on :v, :verbose, "Show the full backtrace"
  opt.on :c, :code, "Show code corresponding to the backtrace frame"
end
process() click to toggle source
# File lib/pry/commands/wtf.rb, line 32
def process
  unless pry_instance.last_exception
    raise Pry::CommandError, "No most-recent exception"
  end

  text = ''.dup
  unwind_exceptions.each_with_index do |exception, i|
    title = (i == 0 ? 'Exception' : 'Caused by')
    text << format_header(title, exception)
    text << format_backtrace(exception.backtrace)
  end
  output.puts(text)
end

Private Instance Methods

format_backtrace(backtrace) click to toggle source
# File lib/pry/commands/wtf.rb, line 64
def format_backtrace(backtrace)
  lines = trim_backtrace(backtrace).map do |frame|
    next frame unless opts.code?

    match = frame.match(RUBY_FRAME_PATTERN)
    code = read_line(match[:file], match[:line].to_i)
    [bold(frame), code].join("\n")
  end

  Pry::Code.new(lines.compact, 0, :text).with_line_numbers.to_s
end
format_header(title, exception) click to toggle source
# File lib/pry/commands/wtf.rb, line 60
def format_header(title, exception)
  "#{bold(title + ':')} #{exception.class}: #{exception}\n--\n"
end
read_line(file, line) click to toggle source
# File lib/pry/commands/wtf.rb, line 83
def read_line(file, line)
  File.open(file, 'r') do |f|
    (line - 1).times { f.gets }
    f.gets
  end
rescue Errno::ENOENT
  nil
end
trim_backtrace(backtrace) click to toggle source
# File lib/pry/commands/wtf.rb, line 76
def trim_backtrace(backtrace)
  return backtrace if opts.verbose?

  size_of_backtrace = [captures[0].size, 0.5].max * 10
  backtrace.first(size_of_backtrace)
end
unwind_exceptions() click to toggle source
# File lib/pry/commands/wtf.rb, line 48
def unwind_exceptions
  exception_list = []
  exception = pry_instance.last_exception

  while exception
    exception_list << exception
    exception = (exception.cause if exception.respond_to?(:cause))
  end

  exception_list
end