How to find where a method is defined at runtime?

We recently had a problem where, after a series of commits had occurred, a backend process failed to run. Now, we were good little boys and girls and ran rake test after every check-in but, due to some oddities in Rails’ library loading, it only occurred when we ran it directly from Mongrel in production mode.

I tracked the bug down and it was due to a new Rails gem overwriting a method in the String class in a way that broke one narrow use in the runtime Rails code.

Anyway, long story short, is there a way, at runtime, to ask Ruby where a method has been defined? Something like whereami( :foo ) that returns /path/to/some/file.rb line #45? In this case, telling me that it was defined in class String would be unhelpful, because it was overloaded by some library.

I cannot guarantee the source lives in my project, so grepping for 'def foo' won’t necessarily give me what I need, not to mention if I have many def foo‘s, sometimes I don’t know until runtime which one I may be using.

10 Answers
10

Leave a Comment