Ruby 块到字符串而不是执行 [英] Ruby block to string instead of executing

查看:67
本文介绍了Ruby 块到字符串而不是执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个例子为例:

write_as_string { puts 'x' }

然后我希望能够做到

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.

动机:创建 DSL,我希望将模拟转换为许多其他方法调用,从调用代码中隐藏 - 使用现有对象和方法而不用猴子修补它们.

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!

谢谢

推荐答案

如果您使用的是 Ruby 1.9,则可以使用 Sourcify gem.它提供了 Proc#to_source,类似于 ParseTree 的 Proc#to_ruby.

If you're on Ruby 1.9, you can use the sourcify gem. It provides Proc#to_source, which is like ParseTree's Proc#to_ruby.

在使用 sourcify 时,如果您在源代码中嵌套了 procs,则可能需要使用 :attached_to 选项来帮助它:

When using sourcify, if you have nested procs in your source code, you might have to help it along with the :attached_to option:

## (Works in Ruby 1.8) Using ParseTree (with parse_tree_extensions)
block.to_ruby
## (Works in Ruby 1.9) Using sourcify
block.to_source
## Try this if you get Sourcify::NoMatchingProcError or Sourcify::MultipleMatchingProcsPerLineError
block.to_source :attached_to => :name_of_block_in_source_code

我发布了关于 ParseTree 和 Ruby 1.9 在我的公司的博客.

I posted about ParseTree and Ruby 1.9 in my company's blog.

这篇关于Ruby 块到字符串而不是执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆