Ruby Mixin


Mixin(Any class {or object} can include a Module, In other word a class that is mixed with a module.) is a class that provides a certain functionality to be inherited or just reused(include/require/load/extent) other module.

When to use mixins?

Use mixins whenever you need to share behaviors between different classes.

Let’s talk about a class:

We can split our code in different classes and inherit them into child class. But problem is that, In ruby, A class can’t  inherit features from more than one parent class, the class is supposed to show multiple inheritance and Ruby does not suppoprt mutiple inheritance.

Let’s talk about a Module:

Modules in ruby are similar to classes, Modules are a way of grouping together methods, classes, and constants. Modules give us  two major benefits:

1.  Modules provide a namespace and prevent name clashes.

2. Modules implement the mixin facility.

But a module is not really a class. You can’t instantiate a Module, and thus it does not have self.

1.  A module can have no instances.

2.  A modu le can have no subclasses.

Mixin:

Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the module.

Sample code to understand of mixin:

Let’s create two module and one test class.

module A
  def a1
    puts 'I am in method a1'
  end
end

module B
  def b1
    puts 'I am in method B1'
  end
end

class Test
  include A
  include B

  def display
    puts 'Modules are included'
  end
end

object=Test.new
object.display
object.a1
object.b1

Outputs:
Modules are included
I am in method a1
I am in method b1

Hope this helps.