tags:

views:

136

answers:

2

Hello,

Take this example:

write_as_string { puts 'x' }

I then want to be able to do

def write_as_string(&block)
  puts block.to_s
end

When I execute this, I want the output to be:

"puts 'x'"

I want to be able to receive the block and get the actual code for the block instead of executing it.

Motivation: Creating a DSL, I want to the mock to be converted into a number of other method calls, hidden from the calling code - using existing objects and methods without monkey patching them.

Any ideas on this would be great!

Thanks

Ben

+1  A: 

You want the ruby2ruby gem, which does this nicely. Unfortunately, to analyze a block this gem depends on ParseTree, which is unsupported in Ruby 1.9.

austinfromboston
That seems cool. But given the following example, I need to somehow get the defined block as a string. How could I do this? ruby = "def a\n puts 'A'\nend\n\ndef b\n a\nend" parser = RubyParser.new ruby2ruby = Ruby2Ruby.new sexp = parser.process(ruby)Or have I missed something?
Ben Hall
if you're not concerned about 1.9 compatibility, i'll recommend @mletterle's answer.
austinfromboston
+2  A: 

Duplicate: http://stackoverflow.com/questions/1675053/printing-a-ruby-block

sudo gem install ParseTree
sudo gem install ruby2ruby

then

require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'

def block_as_string &block
    block.to_ruby
end

results in

irb(main):008:0> block_as_string {puts 'x'}
=> "proc { puts(\"x\") }"
mletterle