1

Possible Duplicate:
ruby inheritance vs mixins

The following is a frequent pattern in Ruby:

module Persistable
  def initialize
    # Initialize a persistable document.
  end
end

class Foo
  include Persistable
end

What's the advantage here over simply subclassing?

class PersistableDocument
  def initialize
    # Initialize a persistable document.
  end
end

class Foo < PersistableDocument
end

In other words, why would you mix in behaviour that defines how an object should be instantiated if all that's accomplished is one extra line of code?

Community
  • 1
  • 1
Hakan Ensari
  • 1,969
  • 1
  • 18
  • 32

1 Answers1

1

Modules should be used when you need to share code for many classes and not only one. Think about the most common module used in Ruby, Enumerable. It expects to be included in an object that implements an each method that accepts a single argument.

Once it is included in such an object, it will provide an implementation for all its methods. So this is the case of using modules, you have a common behavior and you would like to share this behavior with many classes, then you can use a module to implement it.

Modules are not something to replace inheritance, they just allow give you another option to compose the behavior of your objects.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • 1
    Enumerable is far and away the best example of the utility of modules in Ruby. I would simply add that modules are Ruby's solution to multiple inheritance, which poses problems such as: http://en.wikipedia.org/wiki/Diamond_problem. – kwarrick May 29 '12 at 01:54
  • Thanks.I'm talking specifically about the use of Modules where the latter mix in #initialize. – Hakan Ensari May 29 '12 at 02:08