Ruby - Module Modules Mixins

Introduction

An object can access the instance methods of a module by including that module using the include method.

If you were to include MyModule in your program, everything inside that module would pop into the current scope.

So, the greet method of MyModule will now be accessible:

include MyModule

Only instance methods are included.

The greet (instance) method has been included, but the MyModule.greet (module) method has not.

As it's included, the greet instance method can be used just as though it were a normal instance method within the current scope.

The module method, also named greet, is accessed using dot notation:

puts( greet )            #=> I'm happy. How are you?
puts( MyModule.greet )   #=> I'm grumpy. How are you?

The process of including a module is also called mixing in.

Included modules are often called mixins.

When you mix modules into a class definition, any objects created from that class will be able to use the instance methods of the mixed-in module just as though they were defined in the class itself.

Here the MyClass class mixes in the MyModule module:

Demo

module MyModule
    GOODMOOD = "happy"
    BADMOOD = "grumpy"

    def greet#   ww w  .  j av  a2s . c  o  m
        return "I'm #{GOODMOOD}. How are you?"
    end

    def MyModule.greet
        return "I'm #{BADMOOD}. How are you?"
    end
end

class MyClass
    include MyModule

    def sayHi
        puts( greet )
    end

end

ob = MyClass.new
ob.sayHi          #=> I'm happy. How are you?
puts(ob.greet)    #=> I'm happy. How are you?

Result

When including two modules which has duplicate names, Ruby uses the method last defined.

Related Topic