Getting the text (source) of a code block

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.

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’)