Q about instance_eval


#1

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.