使用source_location找到源码位置

1
2
3
4
5
6
7
require 'csv'

p CSV.new('string').method(:flock)
# => #<Method: CSV#flock>

CSV.new('string').method(:flock).source_location
# => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180]

不过source_location这个方法只能用在Ruby 1.9+

如果你是Ruby 1.8.7那么需要安装ruby18_source_location

1
gem install ruby18_source_location
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require 'rubygems'
require 'ruby18_source_location'

def example
  2
end

puts method(:example).source_location.inspect
# => ["/tmp/example.rb", 4]

puts Proc.new{}.source_location.inspect
# => ["/tmp/example.rb", 11]

puts method(:puts).source_location.inspect
# => nil

参考: http://stackoverflow.com/questions/175655/how-to-find-where-a-method-is-defined-at-runtime

原文地址:http://dlj.bz/XiX2mf

Comments