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

(Tuis.) #1
Ruby Foundations | 9

module into a class, Ruby inserts an ICLASS representing the included module into
the including class object’ssuper chain.


For our module inclusion example, let’s simplify things a bit by ignoringBfor now.
We define a module and mix it in toA, which results in data structures shown in
Figure 1-4:


module Mixin
def mixed_method
puts "Hello from mixin"
end
end

class A
include Mixin
end

Here is where the ICLASS comes into play. Thesuperlink pointing fromAtoObject
is intercepted by a new ICLASS (represented by the box with the dashed line). The
ICLASS is a proxy for theMixinmodule. It contains pointers toMixin’siv_tbl
(instance variables) andm_tbl (methods).


From this diagram, it is easy to see why we need proxy classes: the same module may
be mixed in to any number of different classes—classes that may inherit from differ-
ent classes (thus having differentsuperpointers). We could not directly insertMixin
into the lookup chain, because itssuperpointer would have to point to two different
things if it were mixed in to two classes with different parents.


When we instantiateA, the structures are as shown in Figure 1-5:


objA = A.new

Figure 1-4. Inclusion of a module into the lookup chain


Object

Mixin

super

A

super

klass Mixin
Free download pdf