Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
How to Read Code | 51

def bar
pp caller
'baz'
end
end

puts Test.new.foo

This gives us the call stack:


["./call_stack1.8.4.rb:8:in `foo'", "./call_stack1.8.4.rb:17"]
baz

However, this method is clunky. There is very little information that we can use pro-
grammatically; this is mainly for informational use. A more flexible stack trace mecha-
nism comes from Mauricio Fernández’s call_stack library,*which hooks entry and exit
of every method, providing that information at the request of the globalcall_stack
method. This library was developed because Ruby 1.8.5 broke the old implementation
ofBinding.of_caller(which relied on a bug in 1.8.4). However,call_stackworks on
1.8.4 as well. We get much more information throughcall_stack:


#!/usr/local/bin/ruby

require 'rubygems'
require 'call_stack'
require 'pp'

class Test
def foo
bar
end

def bar
pp call_stack(-1)
"baz"
end
end

call_stack_on

puts Test.new.foo

call_stack_off

Thecall_stack_onandcall_stack_offfunctions add and remove the hook func-
tions that keep track of function execution, so you must callcall_stack_onbefore
starting to capture frames. Thecall_stackfunction yields an array of stack frames;
each frame is an array containing [class_name,method_name,filename,line,binding,
language]. This code prints:


*http://eigenclass.org/hiki.rb?call_stack

Free download pdf