Skip to content

Instantly share code, notes, and snippets.

@leandro
Created April 21, 2022 23:45
Show Gist options
  • Save leandro/ef2e480e949ab4369a764b1b0e95fb70 to your computer and use it in GitHub Desktop.
Save leandro/ef2e480e949ab4369a764b1b0e95fb70 to your computer and use it in GitHub Desktop.
An improved version of `p` method for Rails.
module Kernel
def log2(*args)
$log_counter ||= 1
options = args.size > 1 && Hash === args.last ? args.pop : {}
stack_lines = options[:stack_lines] || 1
call_lines = caller(1, stack_lines)
stack_line_stripper = lambda do |line|
stack_line = line[/^.+\/gems\/(.+)$/, 1]
stack_line || line.delete_prefix("#{Rails.root}/")
end
call_line = stack_line_stripper[call_lines.first]
args.each do |arg|
output = "\e[1m\e[37m#{$log_counter.to_s.rjust(5, '0')}\e[0m "\
"\e[31m#{call_line}\e[0m "\
"\e[1m\e[37m->\e[0m "\
"\e[33m#{arg.inspect}\e[0m"
Rails.logger.info(output)
end
call_lines[1..].each do |line|
Rails.logger.info("\e[1m\e[37m\t-> #{stack_line_stripper[line]}\e[0m")
end
$log_counter += 1
args.size == 1 ? args.first : args
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment