Class: Console::Terminal::Formatter::Failure

Inherits:
Object
  • Object
show all
Defined in:
lib/console/terminal/formatter/failure.rb

Overview

Format a failure event, including the exception message and backtrace.

Constant Summary collapse

KEY =

The key used to identify this formatter.

:failure

Instance Method Summary collapse

Constructor Details

#initialize(terminal) ⇒ Failure

Create a new failure formatter.

Parameters:



17
18
19
20
21
22
23
24
25
# File 'lib/console/terminal/formatter/failure.rb', line 17

def initialize(terminal)
  @terminal = terminal
  
  @terminal[:exception_title] ||= @terminal.style(:red, nil, :bold)
  @terminal[:exception_detail] ||= @terminal.style(:yellow)
  @terminal[:exception_backtrace] ||= @terminal.style(:red)
  @terminal[:exception_backtrace_other] ||= @terminal.style(:red, nil, :faint)
  @terminal[:exception_message] ||= @terminal.style(:default)
end

Instance Method Details

#format(event, stream, prefix: nil, verbose: false, **options) ⇒ Object

Format the given event.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/console/terminal/formatter/failure.rb', line 34

def format(event, stream, prefix: nil, verbose: false, **options)
  title = event[:class]
  message = event[:message]
  backtrace = event[:backtrace]
  root = event[:root]
  
  lines = message.lines.map(&:chomp)
  
  stream.puts "  #{prefix}#{@terminal[:exception_title]}#{title}#{@terminal.reset}: #{lines.shift}"
  
  lines.each do |line|
    stream.puts "  #{@terminal[:exception_detail]}#{line}#{@terminal.reset}"
  end
  
  root_pattern = /^#{root}\// if root
  
  backtrace&.each_with_index do |line, index|
    path, offset, message = line.split(":", 3)
    style = :exception_backtrace
    
    # Make the path a bit more readable:
    if root_pattern and path.sub!(root_pattern, "").nil?
      style = :exception_backtrace_other
    end
    
    stream.puts "  #{index == 0 ? "→" : " "} #{@terminal[style]}#{path}:#{offset}#{@terminal[:exception_message]} #{message}#{@terminal.reset}"
  end
  
  if cause = event[:cause]
    format(cause, stream, prefix: "Caused by ", verbose: verbose, **options)
  end
end