6

I have investigated getting the source code of a method if it exists as a file, but without this file reference, is it possible to dynamically print a method's source code? It seems I can access the method signatures in the class with self.methods and each method's .arity. I believe the ri_for gem refers to the original source file.

A better way to frame this question: If a class is extended at runtime, is its source safe from being investigated? Or is the ability to investigate limited to the method signature and the names of the instance variables, maybe the class variables?

Edit: Solution I used: http://seattlerb.rubyforge.org/svn/ruby2ruby/1.2.1/lib/ruby2ruby.rb

class Ruby2Ruby < SexpProcessor  
  def self.translate(klass_or_str, method = nil)  
    sexp = ParseTree.translate(klass_or_str, method)  
    unifier = Unifier.new  
    unifier.processors.each do |p|  
      p.unsupported.delete :cfunc  
    end  
    sexp = unifier.process(sexp)  
    self.new.process(sexp)  
  end   
end  

class Module  
  def to_ruby  
    Ruby2Ruby.translate(self)  
  end  
end  

Paste this in somewhere and you can get a pretty good start on getting the source code out of a class defined at runtime.

Community
  • 1
  • 1
mike
  • 326
  • 1
  • 5
  • 14

2 Answers2

5

There's been talk about a Proc#to_source method for MRI, but AFAIK nothing came of it (yet). There is however the sourcify gem, you should have a look and see if it fits your needs:

https://github.com/ngty/sourcify

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
2

If a class is extended at runtime, is its source safe from being investigated?

No, it is not safe. For example, ParseTree could be used to determine the actual runtime code for the method and reverse-engineer an equivalent implementation.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Thanks, your answer made me check out SexpProcessor and from there I was able to extend the Module class with a ro_ruby method that dumps out the entire class sourcecode. – mike Apr 14 '11 at 13:20