[MUSIC]
Hi and welcome to lecture 12.
In this lecture, we'll discuss modules.
Modules as namespaces, modules as mixins.
We'll talk about built-in Ruby modules and
we'll also talk about the concept of require_relative.
So on the basic level, module really just a container.
It's a container for classes, methods or other modules even.
It's like a Class, but it cannot be instantiated.
So you cannot have an object of a specific module,
like you could have an object, obviously, of a class.
And modules are really used for two main purposes.
One, they use as a namespace or they use as a mix-in.
So to understand the idea of modules and namespace, a lot of languages.
For example, Java will have this idea of a package structure.
So you don't have a name collision between classes.
You will have, for example,
org.packageone.packagetwo and then the class at the end.
Ruby doesn't like having very deep structure, but it is obviously,
nice to have a way that the class names shouldn't collide.
So you shouldn't have a collision, so that's the idea of a namespace.
So for example, you could have a Match class, which makes sense to be part of
a Sports module and you could have a match class that's part of a Patterns module.
And these are completely separate, but
the way instantiate them is instead of just saying Match.new.
Because then you wouldn't know what Match it is, you put them inside a module.
And then you say, for example, module name Sports:: Match.new,
which refers to this class and Patterns::, which refers to this class.
Another way to use modules is as mixins and this is really cool.
So in OO, you have a concept called interfaces.
A lot of languages don't have that.
For example, Java will have a concept of interface.
Which basically, just means a contract requiring a certain group of classes that
abide by a certain contract, which defines what a class could do.
Mixins go a step beyond that, they actually provide a way to share code,
to share a mix-in,
which is why they are called mixins to share code between multiple classes.
Not only that, you could even include built-in modules like
Enumerable that do the hard work for you, as we're gonna see in a minute.
So to see a simple example of a module as a mix-in.
For example, you have modules that's called SayMyName,
which defines accessor, which is a set and a getter.
And just basically, defines a method that says print_name, which prints that name.
And then you can have a person class or
a company class that both include the module SayMyName,
which basically lets you include the functionality inside that module.
So now you could have a person, you could create a person and
then you could set the person name.
Wait a second, but a person doesn't have a name method.
That's okay, because a module does.
So you include the functionality of a module inside the person class.
Same thing with a company.
You include this functionality in a company.