From: Ittay Dror Date: 2008-10-22T18:38:54+09:00 Subject: Re: extending object with another object --------------060608010106080104000203 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Brian Candler wrote: > Ittay Dror wrote: > >> How is it possible to extend an object using another object? >> > > It depends exactly on what you're trying to achieve. > > You have two separate objects, both with their own sets of methods *and* > their own sets of instance variables. In what way do you want to > "extend" the first with the second? What happens to instance variables > belonging to the second object? > I want just to get the methods defined in the second object, something like object.extend(as_module(other_object)) where 'as_module' is some method that returns a module representing the class hierarchy (with singletons) of the other object. class A def initialize(name) @name = name end def hi puts @name end end class B def initialize(name) @name = name end end a = A.new('a') b = B.new('b') b.object_extend(a) b.hi #=> 'b' Ittay > Now, if you simply want a call to method X on object A to be forwarded > to object B (in which context it would use object B's instance > variables), then look at delegate.rb, or you can synthesise this pattern > yourself using method_missing > > class A > def hello > puts "hello" > end > end > > class B > def bye > puts "bye" > end > end > > a = A.new > b = B.new > > # This is a rough implementation of SimpleDelegator > def a.other=(x) > @other=x > end > def a.method_missing(*args) > @other.send(*args) > end > > a.other = b > a.hello > a.bye > > The important thing here is that when methods are delegated to the other > object, they will be in the context of that object and hence have access > to that object's instance variables. Put simply, that object will > "work". > > In cases where the methods by themselves make sense, then generally > you'd stick those methods into a Module so that both a and b could make > use of them. > > class A > include MyStuff > end > ... > b = B.new > b.extend MyStuff > > But clearly you know about this already. > -- Ittay Dror Tikal Tikal Project -- -- Ittay Dror --------------060608010106080104000203--