Ruby modules can be used:
- As a Mixin which shares behavior by including methods from a Module into Classes.
- To create a Namespace that will prevent name collision between Classes and Modules in one's application and the libraries they are using.
See Instructor Notes
If an application has a common name, like Date or Person. It could collide or conflict with another class of the same name in a library being used.
In my Dating application I have a Date class representing a date between people.
And in my Ruby library, gem, I have a Date class representing today or some other day.
Then this will cause a Name Collision. These Date classes represent totally different concepts. But, they will be mixed in together.
And perhaps they MAY have methods of the same name. In which case the last class loaded into Ruby will override the definition of the previous method.
Got an Argument error probably because we're trying to use the wrong method on the wrong Date class.
Wrap the application Date class in a module.
Here we are Namespacing the app's Date class inside the namespace MyDatingApp. And using this namespace when we need the app's Date class.
If you are coming from another language that allows classes to have multiple parents. You will notice that Ruby will only allow you subclass from one other class.
This constraint will prevent the Diamond Problem.
If a subclass, D, inherits from 2 classes, B & C, and B and C both have a method of the same name, sum.
Which method is used when we call the sum method on an instance class D?