Before getting started with modules and mixins, lets first find out theneed of module & mixins in OOP.
In object oriented programming languages multiple inheritance is basic paradigm (child class extends behavior of base class).
C++ supports multiple inheritance.Java does support same using interfaces.
In ruby language, multiple inheritance is achieved very easily using mixin of modules & classes and that makes ruby as powerful language.
Ruby has classes, modules. Modules can be included inside other classes (mixins) to achieve multiple inheritance.
Modules module Greeting # here below is the instance method # and that can be accessed using object of class ONLY def hi puts 'Guest' end end
Module methods can be called using scope resolution operator (::) or dot operator (.)
Greeting::hi# => undefined method `hi’ for Greeting:Module (NoMethodError)It is obivous to have an error because we are calling class method and that is not present inside module.
MixinsLets include greeting module inside person classclass Person include Greetingend
person = Person.newperson.hi #=> “Guest”Lets see how module methods can be defined. It can be done using either self or class_name.module Greeting # here below is the instance method # and that can be accessed using object of class ONLY def hi puts 'Guest' end # Below are module methods # this methods can be invoked # using Greeting::hi # OR Greeting.hi def self.hi puts 'hi Sandip' end # here is one more way to declare # module methods def Greeting.bye puts 'Bye Sandip!' endend
Lets invoke methods
Greeting::hi #=> “hi Sandip”Greeting.bye #=> “Bye Sandip!”Extending class behavior using modulesclass Person def self.included(base) base.extend Greeting endend
Got easy ?? Cheers!