Question

I'm attempting to (for fun and profit) add the ability to inspect objects in ruby and discover their source code. Not the generated bytecode, and not some decompiled version of the internal representation, but the actual source that was parsed to create that object.

I was up quite late learning about Rubinius, and while I don't have my head around it yet fully, I think I've made some progress.

I'm having trouble figuring out how to do this, though. My first approach was to simply add another instance attribute to the AST structures (for, say, a ClosedScope object). Then, somehow pull that attribute out again when the bytecode is interpreted at runtime.

Does this seem like a sound approach?

Was it helpful?

Solution

As Mr Samuel says, you can just use pry and do show-source foo. But perhaps you'd like to know how it works under the hood.

Ruby provides two things that are useful: firstly you can get a list of all methods on an object. Just call foo.methods. Secondly it provides a file_name and line_number attribute for each method.

To find the entire source code for an object, we scan through all the methods and group them by where they are defined. We then scan up the file back until we see class or module or a few other ways rubyists use to define methods. We then scan forward in each file until we have identified the entire class/module definition.

As dgitized points out we often end up with multiple such definitions, if people have monkey patched core objects. By default pry only shows the module definition which contains most methods; but you can request the others with show-source -a.

OTHER TIPS

Have you looked into Pry? It is a Ruby interpreter/debugger that claims to be able to do just what you've asked.

have you tried set_trace_func? It's not rubinius specific, but does what you ask and isn't based on pry or some other gem.

see http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-set_trace_func

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top