Given a Proc object, is it possible to look at the code inside it?
For example:
p = Proc.new{test = 0}
What I need is for some way to get the string "test = 0" from a Proc object that has already been created.
You can use the ruby2ruby library:
>> # tested with 1.8.7
>> require "parse_tree"
=> true
>> require "ruby2ruby"
=> true
>> require "parse_tree_extensions"
=> true
>> p = Proc.new{test = 0}
>> p.to_ruby
=> "proc { test = 0 }"
You can also turn this string representation of the proc back to ruby and call it:
>> eval(p.to_ruby).call
0
More about ruby2ruby in this video: Hacking with ruby2ruby.
In case you're using Ruby 1.9, you can use the sourcify gem
$ irb
ruby-1.9.2-p0 > require 'sourcify'
=> true
ruby-1.9.2-p0 > p = Proc.new{test = 0}
=> #<Proc:0xa4b166c@(irb):2>
ruby-1.9.2-p0 > p.to_source
=> "proc { test = 0 }"
Use proc.source_location
to get the location of the source file that defines the proc.
It also returns the line number of the definition.
You can use those values to locate the location of the proc source.
I think you could use ParseTree for this, it also seems that support for Ruby 1.9.2 is getting close.
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