如何动态获取方法的源代码以及此方法位于哪个文件中 [英] How can I get source code of a method dynamically and also which file is this method locate in

查看:20
本文介绍了如何动态获取方法的源代码以及此方法位于哪个文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以即时获取一个方法的源代码,以及我是否可以获取这个方法在哪个文件中.

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.

喜欢

A.new.method(:a).SOURCE_CODE
A.new.method(:a).FILE

推荐答案

使用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"

请注意,对于内置方法,source_location 返回 nil.如果想查看 C 源代码(玩得开心!),您必须寻找正确的 C 文件(它们或多或少按类组织)并找到 rb_define_method方法(朝向文件末尾).

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

在 Ruby 1.8 中不存在此方法,但您可以使用此 gem.

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

这篇关于如何动态获取方法的源代码以及此方法位于哪个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆