I came from Java, and now I am working more with Ruby.
One language feature I am not familiar with is the module
. I am wondering what exactly is a module
and when do you use one, and why use a module
over a class
?
I came from Java, and now I am working more with Ruby.
One language feature I am not familiar with is the module
. I am wondering what exactly is a module
and when do you use one, and why use a module
over a class
?
Class
When you define a class, you define a blueprint for a data type. class hold data, have method that interact with that data and are used to instantiate objects.
Module
Modules are a way of grouping together methods, classes, and constants.
Modules give you two major benefits:
=> Modules provide a namespace and prevent name clashes. Namespace help avoid conflicts with functions and classes with the same name that have been written by someone else.
=> Modules implement the mixin facility.
Bottom line: A module is a cross between a static/utility class and a mixin.
Mixins are reusable pieces of "partial" implementation, that can be combined (or composed) in a mix & match fashion, to help write new classes. These classes can additionally have their own state and/or code, of course.
Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.
A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.
(This answer originally linked to
http://www.rubycentral.com/pickaxe/classes.html
, but that link and its domain are no longer active.)The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.
For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.
You might also use a module when you have shared methods across multiple apps (again, the library model is good here).