Getting the text (source) of a code block

N

Nit Khair

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.
 
B

Brian Candler

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top