为了账号安全,请及时绑定邮箱和手机立即绑定

如何动态获取方法的源代码以及该方法位于哪个文件中

如何动态获取方法的源代码以及该方法位于哪个文件中

月关宝盒 2019-10-26 11:19:17
我想知道我是否可以即时获取源代码方法,以及是否可以获取该方法位于哪个文件中。喜欢A.new.method(:a).SOURCE_CODEA.new.method(:a).FILE
查看完整描述

3 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

用途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方法的方法(在文件末尾) )。


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


查看完整回答
反对 回复 2019-10-26
?
慕慕森

TA贡献1856条经验 获得超17个赞

没有依赖


method = SomeConstant.method(:some_method_name)

file_path, line = method.source_location

# puts 10 lines start from the method define 

IO.readlines(file_path)[line-1, 10]

如果您想更方便地使用它,可以打开Method该类:


# ~/.irbrc

class Method

  def source(limit=10)

    file, line = source_location

    if file && line

      IO.readlines(file)[line-1,limit]

    else

      nil

    end

  end

end

然后打电话 method.source


根据Pry在codde-browing中的文档,使用Pry,您可以使用show-method来查看方法源,甚至可以看到pry-doc已安装的一些ruby c源代码。


注意,我们也可以使用pry-doc插件查看C方法(从Ruby Core);我们还展示了show-method的替代语法:


pry(main)> show-method Array#select


From: array.c in Ruby Core (C Method):

Number of lines: 15


static VALUE

rb_ary_select(VALUE ary)

{

    VALUE result;

    long i;


    RETURN_ENUMERATOR(ary, 0, 0);

    result = rb_ary_new2(RARRAY_LEN(ary));

    for (i = 0; i < RARRAY_LEN(ary); i++) {

        if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {

            rb_ary_push(result, rb_ary_elt(ary, i));

        }

    }

    return result;

}


查看完整回答
反对 回复 2019-10-26
  • 3 回答
  • 0 关注
  • 559 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信