Skip to content

Instantly share code, notes, and snippets.

@mike-bourgeous
Last active September 17, 2015 00:03
Show Gist options
  • Save mike-bourgeous/d813142bb8b87aad484c to your computer and use it in GitHub Desktop.
Save mike-bourgeous/d813142bb8b87aad484c to your computer and use it in GitHub Desktop.
Quick-and-dirty ANSI highlight of standard Ruby backtraces
puts caller.map{|l|
l.sub(
%r{/([^:/]+):(\d+):in `([^']*)'},
"/\e[33m\\1\e[0m:\e[34m\\2\e[0m:in `\e[1;35m\\1\e[0m'"
)
}
# Returns a String of the message and backtrace with ANSI highlighting and an
# outline in Unicode box drawing characters. The +backtrace+ can also be an
# Exception.
#
# Example:
# puts hl_bt(caller(1), 'Here I am')
def hl_bt(backtrace, msg=nil)
require 'io/console'
if backtrace.is_a?(Exception)
msg = [msg, backtrace.message].compact.join(': ')
backtrace = backtrace.backtrace
color = "\e[31m"
else
color = "\e[34m"
end
width = IO.console.winsize[1] rescue 80
divider = "#{"\u2500" * (width - 3)}\u257c\e[0m"
leader = "#{color}\u2502\e[0m"
str = "#{color}\u256d#{divider}\n"
str << "#{leader}\e[1m#{msg}\e[0m\n" if msg
str << backtrace.reject{|l|
# Skip gems we don't care about
l =~ %r{(gems/(act|factory|rack|rail|state|warden|capybara|rspec|unicorn|newrelic|quiet_assets|meta_request|bullet)|webrick)}
}.map{|l|
# Skip leading paths
l = l[/(rubies|gems).*/] || l
l = l[%r{/gems.*}] || l
# Highlight the line
"#{leader} \e[36m" + l.sub(
%r{/([^:/]+):(\d+):in `([^']*)'},
"/\e[1;33m\\1\e[0m:\e[34m\\2\e[0m:in `\e[1;35m\\3\e[0m'\n"
)
}.join
str << "#{color}\u2514#{divider}\n"
str
end