Modules

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


A module in Ruby is not file-based as it is in Python. It is an object with methods and attributes defined within a module/end block of code, like a class, but without the ability to be instantiated.

 

 module MyModule   # Module names are constants (capitalized)  MyConst = "Module Constant MyModule::MyConst"  $my_global = "Unrelated to module namespace (global is global)"  my_local = "Inaccessible from without"  module NestedModule  # Access via MyModule::NestedModule  end  class InnerClass  end  def module_method  # Can be accessed as MyModule.module_method  end  module_function :module_method end module AnotherModule  # In same file... end 

You can define more than one module in the same source file, and even nest them inside each other to organize your namespace. Loading an external file with module definitions is the same as defining them in the source file, and there is no requirement to give these external files the same name as your module(s).

Once defined in the source file, a module is immediately available. You can access nested modules or constants via the :: scope operator, and module functions (shared public methods) via dot notation. You may also as a whole include the module into a class namespace, or extend any object with its methods. There is no provision for selectively including constants or methods of a module as Python's import allows, because it is considered to be a single unit.

When you use this mixin approach to incorporate such shared code from multiple sources, the included modules become part of the single inheritance tree, similar to a subclass. Yes, order does matter.

 

 class MyString < String end  p MyString.ancestors   # [ MyString, String, ...] module AlterString end  class MyString  include AlterString end  p MyString.ancestors   # [ MyString, AlterString, String, ...] 

The mixin module is not copied but referenced, as in Python.


   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net