In Ruby is there a way to tell where a method is defined? I'm going through the ruby-guides and there is a line of code that reads Post.all
How can I tell where all
is defined?
In Ruby the method for object can be defined from many places: modules, inheritance, meta-programming, other language's extensions and etc. Imagine that you have installed a lot of gems in your application and every gem potentially can define or redefine method on any object.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
early 15c., "regular, systematic treatment of disease," from Latin methodus "way of teaching or going," from Greek methodos "scientific inquiry, method of inquiry, investigation," originally "pursuit, a following after," from meta "in pursuit or quest of" (see meta-) + hodos "a method, system; a way or manner" (of ...
If you want to know the file and line where the method is defined, use
Post.method(:all).source_location
It will give you [file, line]
or nil
if it's a C method.
A method can be used via a Method object. Which at that point as an owner
attribute. So you can do something like this:
puts Post.method(:all).owner
That will tell you the module/class that defines the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With