Read the chapter on Classes and Modules in Programming Ruby by Dave
Thomas. Then read the Rails Plugin - Extending the Rails Core
Functionality by James A. for an indepth coverage on plugins.
I understand which purpose modules serve. My question, however, was if
there’s any
advantage to defining a module for no other purpose than extending a
particular class
instead of just directly changing that class. I hope I didn’t add more
confusion to my
already vague question.
I understand which purpose modules serve. My question, however, was if
there’s any
advantage to defining a module for no other purpose than extending a
particular class
instead of just directly changing that class. I hope I didn’t add more
confusion to my
already vague question.
The end result is more or less the same. However, think of mix-ins as a
way to extend any class with a set of related functionality. In this
respect, a module included into existing classes makes more semantic
sense.
If you adding a single utility method, simply opening the class would be
fine. If you are adding a group of methods that work together toward a
common functional goal, using a module is preferable since it really
helps keep things organized and encapsulated.
Also a module name can be auto-documenting. While the goal of a bunch
of added method to a base class might be unclear, it makes it easier to
understand if the name of the module being included is something
descriptive, such as ActsAsPuppy or GoogleMapsFinder.
If you adding a single utility method, simply opening the class would be
fine. If you are adding a group of methods that work together toward a
common functional goal, using a module is preferable since it really
helps keep things organized and encapsulated.
Also a module name can be auto-documenting. While the goal of a bunch
of added method to a base class might be unclear, it makes it easier to
understand if the name of the module being included is something
descriptive, such as ActsAsPuppy or GoogleMapsFinder.
Thank your very much for your clear description of the pros and cons of
each
approach. This was a much more detailed explanation than I could have
ever
hoped for.
I don’t think you can use the same name ActionController for your
module.
The main idea here is that you once you define a module with your
methods in
it, you can mix-in any of the classes that you wish.
It gives you a multiple-inheritance like behaviour. It provides
namespace
also.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.