Yield, binding


#1

Hi,

I’m experimenting with Ruby by writing some kind of DSL.
I wonder if It is possible calling given block to a proc with different
binding
What I’m trying to achieve is something like this

class Table
attr_accessor :name,
def getBinding
binding
end
end

def table
t = Table.new
if block_given?
yield # with t.getBinding
end
t
end

so I will be able to write (in DSL part)

table {
name = “FirstTable”

}

instead of

table {|t|
t.name = “FirstTable”

}

Thanks

Gokhan E.


#2

On Apr 8, 2006, at 9:40 PM, Gokhan E. wrote:

def getBinding
end
table {|t|

the only way to do this is with eval.

def table(s = nil)
t = Table.new
eval(s, t.getBinding) if s
t
end

table %q{
name = “FirstTable”
}


#3

Gokhan E. wrote:

I’m experimenting with Ruby by writing some kind of DSL.
I wonder if It is possible calling given block to a proc with different
binding

I think you are looking for Object#instance_eval.

Note that in 1.8 there is no way to build-in way to execute a block in a
different context and at the same time providing it with arguments.

In 1.9 it will be possible to do that with Object#instance_exec.


#4

Thanks for the responses.

Now I’m able to read

table {
name “foo”

}

syntax


#5

On 09/04/06, Gokhan E. removed_email_address@domain.invalid wrote:

t.name = “FirstTable”

}

You can’t do ‘name =’, but if you don’t mind a slightly different
setter syntax, you could use this:

class Table
def name(new_name=nil)
@name = new_name if new_name
return @name
end
end

def table(&blk)
t = Table.new
t.instance_eval(&blk) if block_given?
return t
end

t = table{
name “foo”
}

p t #=> #<Table:0x26210 @name=“foo”>

Paul.