Forum: Ruby Q about instance_eval

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.
2c7c807a1df0c76a8fc823c709b501a9?d=identicon&s=25 Victor Shepelev (Guest)
on 2006-06-05 17:55
(Received via mailing list)
Hi all.

I tried some strange kind of things.

class DomNode
  attr_accessor :handler

  def event_handler=(str)
    @handler = eval(str)
  end

  def on_event(*arg); @handler[*arg] end
end

#usage
node.event_handler = 'self["some-attr"] = "some-value"'
node.send_some_event
assert_equal "some-value", self["some-attr"]

OK. Then.

class DomNode
  def clone
    other = DomNode.new
    #some initializing, copying of attributes, etc.
    other.handler = @handler #HERE is the problem!
  end
end

#show the problem:
node.event_handler = 'self["some-attr"] = "some-value"'
cloned = node.clone

cloned.send_some_event
assert_equal "some-value", self["some-attr"] #failed!

Event handler has been evaluated in context of original node; so "self"
is
pointing to original node, not to cloned. So, I need method to "rebind"
proc
to clone, but only if it "binded" to self. How it can be done?

For some reason, I can't do
def on_event(*arg)
  self.instance_eval(&@handler)
end

What can be done instead this?

Thanks.

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