1

This question has been keeping me busy for some time now, so I hope someone has an idea on how to tackle this.

Lets take a simple Class with a method (simplified without an initialize method):

class MyClass
  def my_method
    page.search('//p')
  end
end

Now, is there a way to retrieve the content of my_method without executing it? I am looking to get the code that it will run when executed:

"page.search('//p')"

Is there a way to do that in Ruby?

Severin
  • 8,508
  • 14
  • 68
  • 117
  • Duplicate of http://stackoverflow.com/questions/3393096/how-can-i-get-source-code-of-a-method-dynamically-and-also-which-file-is-this-me ? – Max Williams Nov 20 '14 at 14:12
  • If you do not necessarily need the code as a String, you can also use the AST, for example using the `ast` gem. See also https://www.igvita.com/2008/12/11/ruby-ast-for-fun-and-profit/ which describes the idea (although it is a bit dated). – user4235730 Nov 20 '14 at 14:12

1 Answers1

6

It's possible with pry gem, provided my_method source is saved in some file. pry adds source method to Method class:

require 'pry'
method = MyClass.instance_method(:my_method)
method.source
# => "  def my_method\n    page.search('//p')\n  end"
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91