|
[edit] Ruby Modules
Modules are used for grouping classes into a collection.Modules are very useful when you're writing big applications with a lot of classes.To avoid forgetting which does what and for more efficient management purposes, you can use modules to group classes together depending on the type of functionality they're supposed to provide.
You could have classes for displaying things on screen, classes for user interactivity and so on.Modules even allows you to store them in separate files and use only when you need.
To create a module you need to use the "module" keyword.To tell Ruby you need a certain module for your program to work, you use the "require" keyword, followed by the module's name like this:
module Display
...... <- this is where you put your other class definitions
end
Alternatively, you can save this in a separate file, say mymodule.rb
require Display
...... <- now you can just call a class inside the module you defined earlier like you normally would.
If you saved the module in a separate file, you can call it like this:
require 'mymodule.rb'
...... <- now you can just call a class inside the module you defined earlier like you normally would.
If you're familiar with other programming languages, this should look similar to telling the compiler you need a certain library to be used in order for the program to work, like in C++ for example.
To access a particular method inside a class defined in a module, you call it like this(customized for the example above), with the scope resolution operator, the double ::
Display::CertainMethod.methodcall(parameters required)
Inheritance from multiple modules at once.Mixins
If you ever need to use modules inside a class, this is the way to do it.
Let's take a look at this:
module FirstModule
.......
end
module SecondModule
.....
end
...................
module FinalModule
.....
end
class MainClass
include FirstModule
include SecondModule
......
include FinalModule
end
Obviously useful if you need to either include a lot of modules or if you want to organize your program in even more clean code.
[edit] Ruby Namespaces
The meaning of namespaces is to be understood in close relationship with modules.You can think of a namespace as a trouble-free zone that a module creates for you to be able to you methods or other variables included in classes without causing common errors such as one would expect to happen when using the same name for a variable for example.
The existence of namespaces prevents such problems from happening.This another advantage Ruby has against a very popular object-oriented programming language such as C++.C++ doesn't have such advanced prevention mechanisms implemented yet.
|