Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

10 | Chapter 1: Foundational Techniques


We invoke themixed_method method from the mixin, withobjA as the receiver:


objA.mixed_method
# >> Hello from mixin

The following method-lookup process takes place:


1.objA’s class,A, is searched for a matching method. None is found.


  1. A’ssuperpointer is followed to the ICLASS that proxiesMixin. This proxy object
    is searched for a matching method. Because the proxy’sm_tblis the same as
    Mixin’sm_tbl, themixed_method method is found and invoked.


Many languages with multiple inheritance suffer from thediamond problem, which is
ambiguity in resolving method calls on objects whose classes have a diamond-shaped
inheritance graph, as shown in Figure 1-6.


Given this diagram, if an object of classDcalls a method defined in classAthat has
been overridden in bothBandC, there is ambiguity about which method should be
called. Ruby resolves this by linearizing the order of inclusion. Upon a method call,
the lookup chain is searched linearly, including any ICLASSes that have been
inserted into the chain.


First of all, Ruby does not support multiple inheritance; however, multiple modules
can be mixed into classes and other modules. Therefore,A,B, andCmust be mod-
ules. We see that there is no ambiguity here; the method chosen is the latest one that
was inserted into the lookup chain:


module A
def hello
"Hello from A"
end
end

Figure 1-5. Method lookup for a class with an included module


Object

Mixin

super

A

super

klass Mixin

objA klass
Free download pdf