Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Proc and Method to String [duplicate]

Tags:

ruby

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.

like image 606
juan2raid Avatar asked Jan 26 '11 23:01

juan2raid


4 Answers

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.

like image 172
miku Avatar answered Oct 17 '22 00:10

miku


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 }" 
like image 42
Seamus Abshere Avatar answered Oct 17 '22 00:10

Seamus Abshere


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.

like image 24
Reza Avatar answered Oct 16 '22 23:10

Reza


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

like image 33
Sam Saffron Avatar answered Oct 17 '22 01:10

Sam Saffron