tags:

views:

26

answers:

2

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
+2  A: 

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"

It is new to Ruby 1.9, though. There is no easy solution for Ruby 1.8.

Marc-André Lafortune
A: 

I created the "ri_for" gem for this purpose

 >> require 'ri_for'
 >> A.ri_for :foo

... outputs the source (and location, if you're on 1.9).

GL. -r

rogerdpack
you mean this one http://github.com/rdp/ri_for
allenwei
yep that's the repo for it
rogerdpack