# Getting the text (source) of a code block

**URL:** <https://www.ruby-forum.com/t/getting-the-text-source-of-a-code-block/148703>\
**Category:** Ruby\
**Created:** [September 16, 2008, 1:11pm UTC](https://www.ruby-forum.com/t/getting-the-text-source-of-a-code-block/148703 "2008-09-16T13:11:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sentinel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/fbc32d/32.png) [@sentinel](https://www.ruby-forum.com/u/sentinel)\
**Post date:** [September 16, 2008, 1:11pm UTC](https://www.ruby-forum.com/t/getting-the-text-source-of-a-code-block/148703/1 "2008-09-16T13:11:00Z")

</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:

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

So the hashes object contains a Proc.

---

<div class="post-metadata">

**Author:** ![sentinel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/fbc32d/32.png) [@sentinel](https://www.ruby-forum.com/u/sentinel)\
**Post date:** [September 16, 2008, 1:53pm UTC](https://www.ruby-forum.com/t/getting-the-text-source-of-a-code-block/148703/2 "2008-09-16T13:53:26Z")

</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:

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

block = SrcProc.new “{ |x| puts x+x }”  
block[“hello,”]  
puts block.src

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