Access Pry's show-source method from Ruby file

时间:2019-01-07 13:16:59

标签: ruby-on-rails ruby pry

Is it possible to access Pry's show-source method from within a Ruby file? If so, how is this done?

For example, if I had this file:

# testing.rb

require 'pry' 

def testing
  puts 'hi'
end

puts show-source testing

And ran ruby testing.rb, I'd like the output:

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

def testing
  puts 'hi'
end

To explain the rationale for this, I have a test stubbing a method, though the original seems to be getting called on occassion and I thought it would be handy to output the source of the call to see where it's coming from. I know there are simpler ways of doing this, though started down this rabbit hole and am interested in seeing whether this can be done :)

Running the slightly head-twisting show-source show-source shows a few methods within the Pry::Command::ShowSource class, which inherits from Pry::Command::ShowInfo.

Pry::Command::ShowSource shows three methods: options, process and content_for, though I've not been able to successfully call any.

My best assumption is the content_for method handles this, working with a code object assigned from the parent class (i.e. Pry::CodeObject.lookup(obj_name, _pry_, :super => opts[:super])), though I've not been able to crack this.

Anyone have any ideas or examples of doing this?

2 个答案:

答案 0 :(得分:1)

您可以访问方法的源,而无需将pryObject#methodMethod#source_location结合使用,如此答案所述:https://stackoverflow.com/a/46966145/580346

答案 1 :(得分:1)

Ruby具有内置方法Method#source_location,可用于查找源的位置。 method_source宝石通过基于源位置提取源来在此基础上构建。但是,这不适用于交互式控制台中定义的方法。方法必须在文件中定义。

这里是一个例子:

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.method(:+).source_location #=> nil标准库是用Ruby本身编写的。因此,上面的示例适用于 Set 方法。