Forum: Ruby yield, binding

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7b1c7dac107dcf5ea10dabc38b27ae0d?d=identicon&s=25 Gokhan Ersumer (Guest)
on 2006-04-09 03:40
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 Ersumer
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2006-04-09 03:53
(Received via mailing list)
On Apr 8, 2006, at 9:40 PM, Gokhan Ersumer 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"
}
E0ed615bd6632dd23165e045e3c1df09?d=identicon&s=25 Florian GroÃ? (Guest)
on 2006-04-09 03:56
(Received via mailing list)
Gokhan Ersumer 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.
2abf5beb51d5d66211d525a72c5cb39d?d=identicon&s=25 Paul Battley (Guest)
on 2006-04-09 10:58
(Received via mailing list)
On 09/04/06, Gokhan Ersumer <sky_khan@yahoo.com> 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.
7b1c7dac107dcf5ea10dabc38b27ae0d?d=identicon&s=25 Gokhan Ersumer (Guest)
on 2006-04-10 03:53
Thanks for the responses.

Now I'm able to read

table {
  name "foo"
  ...
}

syntax
This topic is locked and can not be replied to.