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

问题描述 投票:0回答:3

是否可以从 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
显示了三种方法:
options
process
content_for
,尽管我还没有成功调用任何一个。

我最好的假设是

content_for
方法处理这个问题,使用从父类分配的代码对象(即
Pry::CodeObject.lookup(obj_name, _pry_, :super => opts[:super])
),尽管我无法破解这个问题。

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

ruby-on-rails ruby pry
3个回答
6
投票

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 方法。


1
投票

您可以访问方法的源代码,而无需将

pry
Object#method
Method#source_location
一起使用,如本答案所述:https://stackoverflow.com/a/46966145/580346


0
投票

如果您想使用 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"

© www.soinside.com 2019 - 2024. All rights reserved.