Modules Mixins
Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Modules are defined much like classes are, but the module keyword is used in place of the class keyword. Unlike classes, you cannot create objects based on modules nor can you subclass them; instead, you specify that you want the functionality of a particular module to be added to the functionality of a class, or of a specific object. Modules stand alone; there is no "module hierarchy" of inheritance. Modules is a good place to collect all your constants in a central location.
Modules serve two purposes:
- First they act as namespace, letting you define methods whose names will not clash with those defined elsewhere. The examples p058mytrig.rb, p059mymoral.rb, p060usemodule.rb illustrates this.
- Second, they allow you to share functionality between classes - if a class mixes in a module, that module's instance methods become available as if they had been defined in the class. They get mixed in. The program p061mixins.rb illustrates this.
SYNTAX OF require/load VS. SYNTAX OF include - You may have noticed that when you use require or load, you put the name of the item you're requiring or loading in quotation marks, but with include, you don't. require and load take strings as their arguments, whereas include takes the name of a module, in the form of a constant. The requirements to require and load are usually literal strings (in quotation marks), but a string in a variable will also work.
The include method accepts any number of Module objects to mix in:
include Enumerable, Comparable
Although every class is a module, the include method does not allow a class to be included within another class.
Some more examples:
The main difference between inheriting from a class and mixing in a module is that you can mix in more than one module. No class can inherit from more than one class. In cases where you want numerous extra behaviors for a class's instances - and you don't want to stash them all into the class's superclass - you can use modules to organize your code in a more granular way. Each module can add something different to the methods available through the class. Class names tend to be nouns, while module names are often adjectives (like Stack versus Stacklike).
IN RAILS: The Rails source code makes heavy use of modules, in particular the technique of reopening the definition bodies of both classes and modules.