I have a bunch of code to look at, and now it is debugging time. Since I have never been a fan of Ruby’s debugger I am looking for a way of going through code and reading it.
What I am trying to do is get the location of the file where a loaded class is defined:
Foo::Bar.create(:param) # how can I know file location in runtime?
For smaller, better organized, projects, I would just search for class Bar but here that is not possible since there are many classes named Bar, and, to make matters worse, some of them are under the same namespace. I know, it’s trouble waiting to happen.
Note: I’m using Ruby 1.8.7.
For
MethodsandProcsRuby 1.9 has method called source_location:So you can request for the method:
And then ask for the
source_locationof that method:This will return an array with filename and line number.
E.g for
ActiveRecord::Base#validatesthis returns:For classes and modules, Ruby does not offer built in support, but there is an excellent Gist out there that builds upon
source_locationto return file for a given method or first file for a class if no method was specified:EDIT: For Ruby 1.8.7 there is a gem that backports
source_location: