[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Getting the text (source) of a code block

Nit Khair

9/16/2008 11:04:00 AM

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.
--
Posted via http://www.ruby-....

1 Answer

Brian Candler

9/16/2008 11:46:00 AM

0

> 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')
--
Posted via http://www.ruby-....