Using Ruby's Method objects for inspecting methods

Updated . Posted . Visible to the public.

Do you remember finding where a method is defined?

I recently learned from a senior colleague that Method objects Show archive.org snapshot are quite useful within a debugging feast to find out the currently defined internals of methods, because they are either called within the current context or because you want to learn something about the API of the current objects.

Why is this useful?

This is especially useful since Ruby is an interpreted language and the source code and the location might have changed due to the interpretation.


Usage

Before using this, you can examine any ruby object to get it's related methods. Once you know which method you want to inspect, you can create a Method object by calling Object#method. This actually associates it with a particular object and not just with a class.

Now you can use any other methods of the class on that object for further inspections.

Example

# this will give a summary of the received object, the method's signature and it's defined location
slice_method = user.method(:slice)

=> #<Method: User(id: integer, ...)(ActiveRecord::Core)#slice(*methods) /home/path/lib/active_record/core.rb:743>

This way you know whether a method is defined or not, where it is defined and if it is defined the way you expect it to:

# find out the source
slice_method.source
=> "def slice(*methods)\n  ...some code... end\n"

# find out the source location
slice_method.source_location
=> ["/home/some/path/gems/activerecord-6.1.5/lib/active_record/core.rb", 743]

Useful inspections

Useful inspections are

  • #owner: The actual class of the inspected object
  • #parameters: The methods parameters
  • #receiver: The receiving object of the method
  • #super_method: The method of the parent class which would be called by super within the current object
  • #comment: The comment of the method (often includes a short discription)
  • #source: The actual code of the method
  • #source_location: The file path of the method with the exact line

Inheritance

Note that by using #super_method and/or object.class.superclass Show archive.org snapshot you can walk up the inheritance chain and inspect any methods there by following the same approach as displayed above.

Other use cases of the Method objects

Many of the other methods within the Method class are useful for advanced metaprogramming, though this is beyond the scope of this card.


Also see

Felix Eschey
Last edit
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2023-10-09 05:32)