Modules

Class is used to define objects. In Ruby class is derived from Module. Modules is very similar to class with key differences. Modules are used to group methods and variables. Another important usage of the multiple inheritance using a the concept of mixins ( class mixed with module). Modules cannot be however be used to instantiate any object. The basic syntax of the module are as follows:

module PostsHelper

    def author
        ...
    end


    def formatted_date
        ...
    end

end

A module should always start with module key word and the module name should start with Capital letter.

Examples

module FixNumAdder

    def add
        @a + @b
    end

end


class NumberMagic
    include FixNumAdder

    def initialize(a = 0 , b = 0)
        @a = a
        @b = b
    end
end


numbers = NumberMagic.new(10, 20)
puts numbers.add

In this example we create a module and define a method and include it the number magic class.

module FixNumAdder

    def add(a, b)
        a + b
    end

end


class NumberMagic
    extend FixNumAdder
end


puts NumberMagic.add(10, 20)

Here we have used extend method to use the modules method as class method.

module FixNumAdder

    def add
        @a + @b
    end

end



module StringAdder

    def add
        @a.to_s.concat(@b.to_s)
    end

end

We use two different modules to define the method with same name.

class MultiInheritance < MyParentClass
    include FooModule, BarModule, BlahModule\

    ...

end

include can be used for multiple modules.

Leave a Reply

Your email address will not be published. Required fields are marked *