Created
April 29, 2019 15:49
-
-
Save alpaca-tc/7b1b9b0a9a5341131dde16ad4f3c6c9a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .pryrc | |
show_backtrace = Class.new(Pry::ClassCommand) do | |
IGNORE_PATHS = %w[ | |
/pry | |
/byebug | |
].freeze | |
match 'show-backtrace' | |
description 'Filter the caller locations' | |
banner <<-'BANNER' | |
Usage: show-backtrace [NUMBER] | |
show-backtrace | |
show-backtrace 0 | |
BANNER | |
def process | |
if input_index && filtered_backtrace[input_index] | |
location = filtered_backtrace[input_index] | |
edit_file(location) | |
else | |
show_backtrace | |
end | |
end | |
private | |
def show_backtrace | |
out = filtered_backtrace.map { |location| | |
path = Pathname.new(location.path) | |
relative_path = relative_path_from_root(path) | |
"#{relative_path}:#{location.lineno}:in `#{location.label}`" | |
}.map { |line| | |
"\e[31m#{line}\e[0m," | |
}.join("\n") | |
_pry_.pager.page(out) | |
end | |
def relative_path_from_root(path) | |
if defined?(Rails) && Rails.root | |
path.relative_path_from(Rails.root) | |
else | |
path | |
end | |
rescue ArgumentError | |
path | |
end | |
def edit_file(location) | |
_pry_.run_command("edit #{location.path}:#{location.lineno}") | |
end | |
def filtered_backtrace | |
# 3で、このファイルのbacktraceを無視する | |
caller_locations(3).reject do |location| | |
location.path =~ ignore_path_re | |
end | |
end | |
def input_index | |
arg_string.to_i unless arg_string.empty? | |
end | |
def ignore_path_re | |
%r{(?:#{IGNORE_PATHS.join('|')})} | |
end | |
end | |
Pry::Commands.add_command(show_backtrace) | |
Pry::Commands.alias_command '~', 'show-backtrace' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment