juan2raid
juan2raid

Reputation: 1644

How to extract the code from a Proc object?

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.

Upvotes: 20

Views: 9833

Answers (4)

miku
miku

Reputation: 188034

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.

Upvotes: 15

Seamus Abshere
Seamus Abshere

Reputation: 8516

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 }" 

Upvotes: 13

Reza
Reza

Reputation: 1577

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.

Upvotes: 12

Sam Saffron
Sam Saffron

Reputation: 131112

I think you could use ParseTree for this, it also seems that support for Ruby 1.9.2 is getting close.

Upvotes: 2

Related Questions