Ruby on rails 检修撬';从Ruby文件中显示源方法

Ruby on rails 检修撬';从Ruby文件中显示源方法,ruby-on-rails,ruby,pry,Ruby On Rails,Ruby,Pry,可以从Ruby文件中访问Pry的show source方法吗?如果是,如何做到这一点 例如,如果我有此文件: # testing.rb require 'pry' def testing puts 'hi' end puts show-source testing 并运行了ruby testing.rb,我想要输出: Owner: testing.rb Visibility: public Number of lines: 3 def testing puts 'hi' en

可以从Ruby文件中访问Pry的
show source
方法吗?如果是,如何做到这一点

例如,如果我有此文件:

# testing.rb

require 'pry' 

def testing
  puts 'hi'
end

puts show-source testing
并运行了
ruby testing.rb
,我想要输出:

Owner: testing.rb
Visibility: public
Number of lines: 3

def testing
  puts 'hi'
end
为了解释这一点的基本原理,我对一个方法进行了一个测试,尽管最初的方法似乎是在偶然的时候被调用的,我认为输出调用的源代码以查看它来自何处是很方便的。我知道有更简单的方法可以做到这一点,尽管我是从这个兔子洞开始的,我很想看看是否可以做到:)

运行稍微扭曲的
show source show source
显示了
Pry::Command::ShowSource
类中的一些方法,这些方法继承自
Pry::Command::ShowInfo

Pry::Command::ShowSource
显示了三种方法:
选项
过程
内容_,尽管我还无法成功调用任何方法

我最好的假设是
content\u for
方法处理这个问题,使用从父类分配的代码对象(即
Pry::CodeObject.lookup(obj\u name,\u Pry,:super=>opts[:super])
,尽管我还没能破解这个问题


任何人都有这样做的想法或例子吗?

您可以访问方法的源代码,而无需使用
pry
方法#源位置
,如下面的回答所述:

Ruby具有内置方法,可用于查找源代码的位置。gem通过基于源位置提取源来构建此模型。但是,这不适用于交互式控制台中定义的方法。方法必须在文件中定义

以下是一个例子:

require 'set'
require 'method_source'

set_square_bracket_method = Set.method(:[])

puts set_square_bracket_method.source_location
# /home/user/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/set.rb
# 74
#=> nil

puts set_square_bracket_method.source
# def self.[](*ary)
#   new(ary)
# end
#=> nil

请记住,所有核心Ruby方法都是用C编写的,并返回
nil
作为源位置<代码>1.方法(:+).source_location#=>nil
标准库是用Ruby本身编写的。因此,上述示例适用于集合方法。

Perfect-谢谢@JohanWentholt。这完全符合我的要求。感谢你的回答。