ruby-on-railsrubypry

Access Pry's show-source method from Ruby file


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?


Solution

  • Ruby has the build-in method Method#source_location which can be used to find the location of the source. The method_source gem builds upon this by extracting the source based upon the source location. However this doesn't work for methods defined in the interactive console. Methods must be defined in a file.

    Here is an example:

    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
    

    Keep in mind that all core Ruby methods are written in C and return nil as source location. 1.method(:+).source_location #=> nil The standard library is written in Ruby itself. Therefore the example above works for Set methods.