Ittay D. 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?
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
a = A.new
b = B.new
This is a rough implementation of SimpleDelegator
a.other = b
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
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.
b = B.new
But clearly you know about this already.