Get current stack trace in Ruby without raising an exception

JellicleCat picture JellicleCat · Jun 20, 2012 · Viewed 55.2k times · Source

I want to log the current backtrace (stacktrace) in a Rails 3 app without an exception occurring. Any idea how?

Why do I want this? I'm trying to trace the calls that are made when Rails looks for a template so that I can choose a part of the process to override (because I want to change the view path for a particular subclassed controller of mine).

I'd like to call it from the file: gems\actionpack-3.2.3\lib\action_dispatch\middleware\templates\rescues\missing_template.erb. I know that's not best practice, but I know it's downstream of the stack from where the search for templates occurs.

Answer

KL-7 picture KL-7 · Jul 2, 2012

You can use Kernel#caller:

# /tmp/caller.rb

def foo 
  puts caller # Kernel#caller returns an array of strings
end

def bar 
  foo 
end

def baz 
  bar 
end

baz

Output:

caller.rb:8:in `bar'
caller.rb:12:in `baz'
caller.rb:15:in `<main>'