Skip to content

Instantly share code, notes, and snippets.

@ajhekman
Created May 7, 2016 21:45
Show Gist options
  • Save ajhekman/b88e7055b6116fb32644736db3c16f80 to your computer and use it in GitHub Desktop.
Save ajhekman/b88e7055b6116fb32644736db3c16f80 to your computer and use it in GitHub Desktop.
Simple inline debugger
require 'pathname'
require 'pry'
# Usage:
#
# class YourClass
# include Debugger
# debugger_namespace "TheNamespace" # optional, defaults to file basename
# debugger_show_line_numbers # optional
#
# def basic_printing_example
# debug 'message'
# # > TheNamespace:18 message
#
# debug [1,2,3,4]
# # > TheNamespace:20 [1, 2, 3, 4]
# end
#
# def open_pry_if_block_is_falsy
# debug("debug message") { falsy_block }
# # > TheNamespace:25 debug message
# # pry(main)> (opens at debug call site)
# end
# end
module Debugger
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def debugger_namespace(namespace)
@@debugger_namespace = namespace.to_s
end
def debugger_show_line_numbers(show = true)
@@debugger_show_line_numbers = show
end
def debug(msg = :no_msg, &blk)
loc = caller_locations(1, 1).first
debugger_process_debug(loc, msg, &blk)
end
def debugger_process_debug(loc, msg, &blk)
puts debug_message(loc, msg)
return unless block_given?
our_binding = blk.binding
res = blk.call
return our_binding.pry unless res
end
private
def cyan(str)
"\e[0;36m" +
str +
"\e[0;0m"
end
def debugger_namespace_name(loc)
unless defined? @@debugger_namespace
return Pathname.new(loc.path).basename.to_s
end
@@debugger_namespace
end
def debugger_line_numbers(loc)
return '' unless defined? @@debugger_show_line_numbers
":#{loc.lineno}"
end
def debugger_user_message(msg)
return '' if msg == :no_msg
' ' + msg.to_s
end
def debug_message(loc, msg)
cyan(debugger_namespace_name(loc)) +
debugger_line_numbers(loc) +
debugger_user_message(msg)
end
end
def debug(msg = :no_msg, &blk)
loc = caller_locations(1, 1).first
self.class.debugger_process_debug(loc, msg, &blk)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment