Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get source code of a method dynamically and also which file is this method locate in

Tags:

ruby

I would like to know whether I can get source code a method on the fly, and whether I can get which file is this method in.

like

A.new.method(:a).SOURCE_CODE A.new.method(:a).FILE 
like image 820
allenwei Avatar asked Aug 03 '10 01:08

allenwei


1 Answers

Use source_location:

class A   def foo   end end  file, line = A.instance_method(:foo).source_location # or file, line = A.new.method(:foo).source_location puts "Method foo is defined in #{file}, line #{line}" # => "Method foo is defined in temp.rb, line 2" 

Note that for builtin methods, source_location returns nil. If want to check out the C source code (have fun!), you'll have to look for the right C file (they're more or less organized by class) and find the rb_define_method for the method (towards the end of the file).

In Ruby 1.8 this method does not exist, but you can use this gem.

like image 55
Marc-André Lafortune Avatar answered Sep 19 '22 17:09

Marc-André Lafortune