Created
March 29, 2012 15:13
-
-
Save mtgrosser/2238359 to your computer and use it in GitHub Desktop.
irb_debugger - Debugging with IRB on Ruby 1.9.x, no extra gems required!
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
# irb_debugger - A very simple debugger based on IRB | |
# | |
# As long as ruby-debug19 is broken, you can put this in your lib folder | |
# and require it in your test.rb or development.rb files. | |
# This will enable you to start an IRB session within your application, | |
# wherever you need it! Just write | |
# | |
# irb_debugger {} | |
# | |
# and it will fire IRB with full access to the current binding, i.e. | |
# all variables etc. will be present. Just remember the block is essential! | |
require 'irb' | |
module IRB | |
def self.start_debug_session(debug_binding) | |
unless @__initialized | |
args = ARGV | |
ARGV.replace(ARGV.dup) | |
Kernel.silence_warnings { IRB.setup(nil) } | |
ARGV.replace(args) | |
@__initialized = true | |
end | |
file = debug_binding.eval('__FILE__') | |
line = debug_binding.eval('__LINE__') | |
if File.exist?(file) | |
start = [0, line - 5].max | |
lines = File.readlines(file)[start..(line + 5)] | |
width = Math.log10((start + 10)).to_i | |
format = "%0#{width}u" | |
puts "\nIn file #{file}:" | |
lines.each_with_index do |code, idx| | |
arrow = line == start + idx + 1 ? '-> ' : ' ' | |
puts "#{arrow}#{format % (idx + start)}: #{code.rstrip}" | |
end | |
puts '' | |
end | |
workspace = WorkSpace.new(debug_binding) | |
irb = Irb.new(workspace) | |
@CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] | |
@CONF[:MAIN_CONTEXT] = irb.context | |
catch(:IRB_EXIT) do | |
irb.eval_input | |
end | |
end | |
end | |
module Kernel | |
def irb_debugger(&block) | |
if block_given? | |
IRB.start_debug_session(block.binding) | |
else | |
puts 'No block given! USAGE: irb_debugger {}' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment