从Ruby文件访问Pry的show-source方法

hmmo2u0o  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(83)

是否可以从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显示了三种方法:optionsprocesscontent_for,尽管我无法成功调用任何一个。
我最好的假设是content_for方法处理这个问题,使用从父类(即Pry::CodeObject.lookup(obj_name, _pry_, :super => opts[:super])),虽然我还没能破解这个。
有人有这样做的想法或例子吗?

hts6caw3

hts6caw31#

Ruby有一个内置的方法 Method#source_location,可以用来查找源代码的位置。method_source gem通过基于源位置提取源代码来构建此基础。但是,这不适用于交互式控制台中定义的方法。方法必须在文件中定义。
下面是一个示例:

require 'set'
require 'method_source'

puts Set.method(:[]).source_location
# /home/user/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/set.rb
# 74
#=> nil

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

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

bvjveswy

bvjveswy2#

您可以访问方法的源代码,而无需使用pry与Object#方法和Method#source_location,如以下答案所述:https://stackoverflow.com/a/46966145/580346

7lrncoxx

7lrncoxx3#

如果你想使用Pry来显示一个方法的源代码(而不仅仅是源代码的位置):

require "pry"

identifier = "MyClass#my_instance_function"
code_object = Pry::CodeObject.lookup(identifier, Pry.new)

puts code_object.source # => ...
# def my_instance_function(arg)
#   puts "my arg #{arg}
# end

.其中identifier是方法的标准Pry标识符,例如"MyClass#my_instance_method""MyNamespace.my_static_function"

相关问题