Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make ruby print the source code for a dynamic method?

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.

like image 257
mike Avatar asked Apr 07 '11 20:04

mike


2 Answers

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

like image 177
Michael Kohl Avatar answered Nov 19 '22 11:11

Michael Kohl


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.

like image 22
Phrogz Avatar answered Nov 19 '22 11:11

Phrogz