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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With