Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby get backtrace without an exception

I have a Ruby on Rails application where a validation is failing for one of my models. There are different entry points into the code base for where this validation could fail. I'm interested in figuring out where it's coming from. Since it is a simple validation method, there aren't any exceptions involved, I just return false from the method and the save fails.

Is it currently possible to also log the backtrace to figure out what service/route this validation originated from so I can see what caused the state to change for this object in order for it to fail validation?

like image 212
randombits Avatar asked Aug 10 '12 18:08

randombits


2 Answers

You could try caller():

def foo2
  puts caller
end
def foo
  foo2   #line5
end 
foo     #line 7

Result:

test.rb:5:in `foo'
test.rb:7:in `<main>'
like image 103
knut Avatar answered Oct 13 '22 22:10

knut


I'm not sure of a clever way to do it, but this will get the job done. You could wrap it in a nice little function even. I'm not sure if throwing exceptions and rescuing them will impact performance, but you probably wouldn't want to do something like this in production.

begin
  throw
rescue
  puts $!.backtrace
end
like image 31
CambridgeMike Avatar answered Oct 13 '22 21:10

CambridgeMike