# Getting the text (source) of a code block

**URL:** <https://rubytalk.org/t/getting-the-text-source-of-a-code-block/49115>\
**Category:** ruby-talk\
**Created:** [16 September 2008 11:03 UTC](https://rubytalk.org/t/getting-the-text-source-of-a-code-block/49115 "2008-09-16T11:03:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![\_RK\_Sentinel](https://avatars.discourse-cdn.com/v4/letter/_/45deac/32.png) [@\_RK\_Sentinel](https://rubytalk.org/u/_RK_Sentinel)\
**Post date:** [16 September 2008 11:03 UTC](https://rubytalk.org/t/getting-the-text-source-of-a-code-block/49115/1 "2008-09-16T11:03:40Z")

</div>

I am writing a ruby DSL and generating code from it. The DSL spec  
contains code blocks -- ordinarily these are getting stored as Procs.  
However, since I am generating code, I would like to take the source and  
print/store it.

It occurs to me that the user should probably store the block as a  
heredoc or string, but that could result in code duplication later, and  
not allow me to make a change later. Later, I might decide to execute  
the app rather than generate code.

So can i extract the source of the block?

Currently my code looks like this:

&nbsp;&nbsp;def method\_missing(id, \*args, &block)  
&nbsp;&nbsp;&nbsp;&nbsp;...  
&nbsp;&nbsp;&nbsp;&nbsp;if block  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashes[...]=block  
&nbsp;&nbsp;&nbsp;&nbsp;else  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashes[...]=args  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

So the hashes object contains a Proc.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [16 September 2008 11:46 UTC](https://rubytalk.org/t/getting-the-text-source-of-a-code-block/49115/2 "2008-09-16T11:46:18Z")

</div>

> It occurs to me that the user should probably store the block as a  
> heredoc or string, but that could result in code duplication later

You can use eval to turn the string into a block:

&nbsp;&nbsp;class SrcProc  
&nbsp;&nbsp;&nbsp;&nbsp;attr\_reader :src  
&nbsp;&nbsp;&nbsp;&nbsp;def initialize(src)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@src = src  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@proc = eval "lambda #{src}"  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;def call(\*args,&blk)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@proc.call(\*args,&blk)  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;alias : :call  
&nbsp;&nbsp;end

&nbsp;&nbsp;block = SrcProc.new "{ |x| puts x+x }"  
&nbsp;&nbsp;block["hello,"]  
&nbsp;&nbsp;puts block.src

I believe that going in the opposite direction is much harder (google  
for 'parsetree')

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
