Max Williams
Max Williams

Reputation: 32955

How to get the method which is handling a method call

I have an app which uses Ruby 1.8. 6 in a Rails 2.2.2 app.

It has many definitions of the method url_for in various parts of the code base (classes, modules etc).

When debugging, I'd like to see in the log which method handles a specific call to url_for. E.g.,

foo = "bar"
baz = url_for(foo)
#would like to log the location of the url_for method which actually 
#handled the call, here.

It's fine if the only way to do this is to raise an exception inside url_for and look at the stack trace, eg

baz = url_for(something_which_wont_raise_here_but_will_raise_inside_the_url_for_method)

To go further, what if the method is being called on an instance of a (heavily patched) class:

foo = @baz.bar("qux")

EDIT: I didn't specify that it was Ruby 1.8.6 in my question, and it looks like i can't use the .source_location method. Very sorry about not specifying the version earlier! Does anyone have any other ideas?

Upvotes: 3

Views: 59

Answers (3)

sawa
sawa

Reputation: 168249

If you do:

method(:url_for).owner

It will give you the module/class in which the method is defined. This should be enough to let you identify the method (unless the same method is redundantly defined in the same module multiple times). You can then look at the definition of url_for in that module/class.

Upvotes: 1

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

You can use method and source_location methods chain to get the location of the method definition.

For example:

Example

Upvotes: 1

Frederick Cheung
Frederick Cheung

Reputation: 84182

It sounds like you want to do

method(:url_for)

to get a Method object, and then use source_location to find out where it was defined

Upvotes: 2

Related Questions