I'm trying to write a debugger in ruby. I want to run some code every time a variable changes. I don't know the variables in advance.
At the moment I'm trying set_trace_func but it seems to execute before each line, rather than after each line eg;
set_trace_func proc { |event, file, line, id, binding, classname|
if file == "(eval)"
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
args = binding.eval("local_variables").inject({}) do |vars, name|
value = binding.eval name.to_s
vars[name] = value unless vars.nil?
vars
end
puts args.inspect
end
}
eval("blah = 4\nrar = 3\n")
set_trace_func(nil)
When I execute it I get;
n@VirtualBox:~$ ruby blah.rb
line (eval):1
{:blah=>nil, :rar=>nil}
line (eval):2
{:blah=>4, :rar=>nil}
n@VirtualBox:~$
This is not what I want - it's not showing the assignment to rar. Is there a better way to do this? As a hack, I added one last statement to the eval eg.
eval("blah = 4\nrar = 3\nnil\n")
but that doesn't fix the problem when it comes to loops etc.
I would like to get an output of what line a variable changed on and what it changed to in order.