Getting a backtrace in Ruby
Here’s a handy trick I found while trying to practice more of “red-green-refactor”, a method that will dump the stack of every thread without halting the application. Note that this trick uses fork(), so Windows Rubyists are out in the cold (all three of them).
def dump_stacks
fork do
ObjectSpace.each_object(Thread) do |th|
th.raise Exception, "Stack Dump" unless Thread.current == th
end
raise Exception, "Stack Dump"
end
end
fork do
ObjectSpace.each_object(Thread) do |th|
th.raise Exception, "Stack Dump" unless Thread.current == th
end
raise Exception, "Stack Dump"
end
end
This is courtesy of Robert Klemme, via the Ruby Talk mailing list