Chapter 4. Modules and program organization

 

This chapter covers

  • Encapsulation of behavior in modules
  • Modular extension of classes
  • The object method-lookup path
  • Handling method-lookup failure
  • Establishing namespaces with modules and nesting

This chapter will introduce you to a Ruby construct that’s closely related to classes: modules. As their name suggests, modules encourage modular design: program design that breaks large components into smaller ones and lets you mix and match object behaviors.

Like classes, modules are bundles of methods and constants. Unlike classes, modules don’t have instances; instead, you specify that you want to add the functionality of a particular module to that of a class or of a specific object.

It’s no accident that modules are similar in many respects to classes: the Class class is a subclass of the Module class, so every class object is also a module object. We discussed classes first because Ruby is object-centric and objects are instances of classes. But you could say that modules are the more basic structure, and classes are just a specialization. The bottom line is that they’re both part of Ruby, and both are available to you as you design your programs and model your data.

Looking at modules takes us further along some paths we partially walked in the previous chapter:

4.1. Basics of module creation and use

4.2. Modules, classes, and method lookup

4.3. The method_missing method

4.4. Class/module design and naming

Summary

sitemap