Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check what class implements specified method in Ruby?

Tags:

ruby

In one of Ruby examples I see the following code:

require 'net/http'
req = Net::HTTP::Get.new( "http://localhost:8080/" )
req.basic_auth( "user", "password" )

What is the easiest way to know what Ruby class actually implements this basic_auth method or is it dynamically generated? I have checked public_methods of Net::HTTP::Get and it's definitely not there. But how to check what class actually implements it?

like image 367
grigoryvp Avatar asked Nov 26 '25 19:11

grigoryvp


1 Answers

Generally, you would use the Kernel#method method to get the Method object for the method in question and then you would use the Method#owner method to ask the Method object where it was defined.

So,

req.method(:basic_auth).owner
# => Net::HTTPHeader

should answer your question.

Except, in this particular case, that won't work because req is a Net::HTTP::Get object and Net::HTTP::Get overrides the method method to mean something completely different. In particular, it doesn't take an argument, thus the above code will actually raise an ArgumentError.

However, since Net::HTTP::Get inherits from Object and Object mixes in Kernel, it is legal to bind the Kernel#method method to an instance of Net::HTTP::Get:

Kernel.instance_method(:method).bind(req).(:basic_auth).owner
# => Net::HTTPHeader

So, there's your answer: the method is defined in Net::HTTPHeader.

like image 125
Jörg W Mittag Avatar answered Nov 29 '25 16:11

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!