如何动态获取方法的源代码以及此方法所在的文件

all*_*wei 83 ruby

我想知道我是否可以动态获取源代码源代码,以及我是否可以获取此方法的文件.

喜欢

A.new.method(:a).SOURCE_CODE
A.new.method(:a).FILE
Run Code Online (Sandbox Code Playgroud)

Mar*_*une 111

用途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"
Run Code Online (Sandbox Code Playgroud)

不过,这是Ruby 1.9的新功能.对于Ruby 1.8,你可以使用这个gem,我将把这个代码复制到source_location我得到的时候.

  • 嗨,我来自未来,使用Ruby 2.6.1!我想要`String#include?`的源代码。到目前为止,`String.instance_method(:include?)。source_location`返回`nil`。 (2认同)
  • @ S.Goswami答案已编辑。祝好运 (2认同)

Til*_*ilo 36

到目前为止,没有一个答案显示如何动态显示方法的源代码......

实际上,如果你使用John Mair(Pry的制造商)提供的'method_source'宝石,这实际上非常容易:该方法必须在Ruby(而不是C)中实现,并且必须从文件(而不是irb)加载.

这是一个使用method_source在Rails控制台中显示方法源代码的示例:

  $ rails console
  > require 'method_source'
  > I18n::Backend::Simple.instance_method(:lookup).source.display
    def lookup(locale, key, scope = [], options = {})
      init_translations unless initialized?
      keys = I18n.normalize_keys(locale, key, scope, options[:separator])

      keys.inject(translations) do |result, _key|
        _key = _key.to_sym
        return nil unless result.is_a?(Hash) && result.has_key?(_key)
        result = result[_key]
        result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
        result
      end
    end
    => nil 
Run Code Online (Sandbox Code Playgroud)

也可以看看:


Aut*_*ico 16

以下是如何从ruby打印出源代码:

puts File.read(OBJECT_TO_GET.method(:METHOD_FROM).source_location[0])
Run Code Online (Sandbox Code Playgroud)


fan*_*ing 9

没有依赖

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]
Run Code Online (Sandbox Code Playgroud)

如果你想更方便地使用它,你可以打开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
Run Code Online (Sandbox Code Playgroud)

然后打电话 method.source

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

请注意,我们还可以使用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;
}
Run Code Online (Sandbox Code Playgroud)