Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby is there a way to tell where a method is defined?

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?

like image 534
lampShade Avatar asked Dec 18 '11 21:12

lampShade


People also ask

Where method is defined Ruby?

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.

Do you know what a class method is and how do you define one Ruby?

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.

Where does method come from?

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 ...


2 Answers

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.

like image 189
Reactormonk Avatar answered Sep 21 '22 21:09

Reactormonk


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.

like image 28
ctcherry Avatar answered Sep 19 '22 21:09

ctcherry