Some basic knowledge about modules in Ruby and basic knowledge about Ruby modules
A module is similar to a class. It can also be called a class that cannot be instantiated ". Because the Class is a subclass of the Module Class, it may be better to say "Class = Module + instantiation Capability.
What is the so-called module used? There are two main types of functions: Mix-in and namespace.
Mix-in is actually a restricted multi-inheritance. By using the actual inheritance relationships, we can "embellish" some classes. In fact, Mix-in comes from cookies or nuts on ice cream.
In the history of object-oriented design, problems caused by multiple inheritance mechanisms have long been well known. Therefore, many modern object-oriented design languages only support a single inheritance method. Ruby adopts this method.
However, the multi-Inheritance Mechanism also has the charm that cannot be left behind. Therefore, Ruby introduces many advantages of multi-inheritance by using Mix-in.
If a class inherits multiple classes at the same time, many problems may occur in the object-oriented design. Therefore, Ruby has the following restrictions:
1. Only one class can be inherited
2. You can inherit from multiple so-called "class but not class" modules.
In addition, Ruby calls the include action of "adding modules to classes.
Another function of the module is to provide a namespace.
In large-scale program development, naming conflicts often occur. For example, the reader needs to create a class named Service in the program, but the Service name has already been used in the library. This is the issue of Name Conflict.
In many modern programming languages, namespace or package functions are basically provided to avoid naming conflicts. Although the Service classes in different namespaces have the same class names, they are processed as different objects.
In Ruby, modules are usually used to provide such namespaces.
class Service; endmodule Library class Service; endend
The first Service class belongs to the Top Level namespace, and the subsequent Service class belongs to the Library module.
This is actually the constant named Service defined in the Top Level and Library modules respectively (the class name is actually a constant pointing to the class object ).
Therefore, it is used like a constant.
: Service # Top Level ServiceLibrary: Service # Library Service