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

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

The best way to formulate this question is: if a class is extended at runtime, is its source safe for research? Or is it the ability to examine the limited method signature and instance variable names, possibly class variables?

Edit: The 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 somewhere, and you can get a good start to get the source code from the class defined at runtime.

+6
source share
2 answers

If a class is extended at runtime, its source cannot be examined?

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

+2
source

There was talk of a Proc#to_source for MRI, but AFAIK did not work (yet). However, there is a sourcify , you should look and see if it fits your needs:

https://github.com/ngty/sourcify

+5
source

Source: https://habr.com/ru/post/885455/


All Articles