Can I access the binding at the time of the exception in Ruby

Let's say I have:

begin 2.times do a = 1 1/0 end rescue puts $! debugger end 

In this example, I want to get the value of a . If a initialized in a begin block, then I can access it when saving. However, in this example, a is block-local. Is there any way to get a binding at the time of the exception when I save?

+7
source share
2 answers

Can you add another begin , rescue block inside the do block?

+1
source

It seems like it could be hacked. This is not very nice, though:

 class Foo < Exception attr_reader :call_binding def initialize # Find the calling location expected_file, expected_line = caller(1).first.split(':')[0,2] expected_line = expected_line.to_i return_count = 5 # If we see more than 5 returns, stop tracing # Start tracing until we see our caller. set_trace_func(proc do |event, file, line, id, binding, kls| if file == expected_file && line == expected_line # Found it: Save the binding and stop tracing @call_binding = binding set_trace_func(nil) end if event == :return # Seen too many returns, give up. :-( set_trace_func(nil) if (return_count -= 1) <= 0 end end) end end class Hello def a x = 10 y = 20 raise Foo end end class World def b Hello.new.a end end begin World.new.b rescue Foo => e b = e.call_binding puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect end 

Source: How to get initial values โ€‹โ€‹and variable values โ€‹โ€‹in ruby โ€‹โ€‹tracebacks?

0
source

All Articles