Ray's playground

 

Sharing Functionality: Inheritance, Modules, and Mixins(Chapter 5 of Programming Ruby)

  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.
  • Modules support the mixin facility.

  You can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses. 

 

mixin
 1 module Debug
 2   def who_am_i?
 3     "#{self.class.name} (\##{self.object_id}): #{self.to_s}"
 4   end
 5 end
 6 
 7 class Phonograph
 8   include Debug
 9   # ...
10 end
11 
12 class EightTrack
13   include Debug
14   # ...
15 end
16 
17 ph = Phonograph.new("West End Blues")
18 et = EightTrack.new("Surrealistic Pillow")
19 ph.who_am_i? # => "Phonograph (#330450): West End Blues"
20 et.who_am_i? # => "EightTrack (#330420): Surrealistic Pillow"

 

 

 

  One of the other questions folks ask about mixins is, how is method lookup handled? In particular, what happens if methods with the same name are defined in a class, in that class’s parent class, and in a mixin included into the class?

  The answer is that Ruby looks first in the immediate class of an object, then in the mixins included into that class, and then in superclasses and their mixins. If a class has multiple modules mixed in, the last one included is searched first. 

posted on 2010-06-28 12:43  Ray Z  阅读(265)  评论(0编辑  收藏  举报

导航