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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.