When a class includes a module, that module's instance methods become
available as instance methods of the class. It's almost as if the
module becomes a superclass of the class that uses it. Not
surprisingly, that's about how it works. When you include a module,
Ruby creates an anonymous proxy class that references that module, and
inserts that proxy as the direct superclass of the class that did the
including. The proxy class contains references to the instance
variables and methods of the module. This is important: the same
module may be included in many different classes, and will appear in
many different inheritance chains. However, thanks to the proxy
class,
there is still only one underlying module: change a method definition
in that module, and it will change in all classes that include that
module, both past and future.
module SillyModule
|
def hello
|
"Hello."
|
end
|
end
|
class SillyClass
|
include SillyModule
|
end
|
s = SillyClass.new
|
s.hello
|
� |
"Hello."
|
module SillyModule
|
def hello
|
"Hi, there!"
|
end
|
end
|
s.hello
|
� |
"Hi, there!"
|
The relationship between classes and the modules they include is shown
in Figure 19.4 on page 243. If multiple modules are included, they
are added to the chain in order.
If a module itself includes other modules, a chain of proxy classes
will be added to any class that includes that module, one proxy for
each module that is directly or indirectly included.