Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Modules

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 230
    Comment on it

    One of the most powerful feature in ruby is module. Modules are like classes but can not instantiated. Module is used for two purpose:

     

    1. namespacing
    2. mixin

     

    Namespacing

    A class per can be wrapped inside a module to avoid collision.  Suppose I create a library which has a Person class. If you use that library in a program which already has an Person class, the two class definitions will merge together causing unexpected behavior.

    class Person
    end

     

    This Person class can be accessed by class name and instantiated by:

    Person.new

     

    Now another Person class inside MyModule

    module MyModule
      class Person
      end
    end

     

    It can be accessed by MyModule::Person  and instantiated by:

    MyModule::Person.new


    The primary purpose of namespacing classes is to avoid collision. If I write a library that has an Asset class, for instance, and you use my library in a program which already has an Asset class, the two class definitions will merge into one Frankenstein class, usually causing unexpected behavior.


    Mixin in ruby

    Rails support single inheritance. So one class can not inherit features from more than one class. But there is a mixin feature that can be used to inherit features from mutiple modules.

    We create two modules Utils and Logs. Now we include both the modules in Person class. All methods in modules are now available to Person class objects.

    module Utils
      def sayHello
        puts "hello i am mixin feature"
      end
    end
    
    
    module Logs
      def log
        puts "creating logs"
      end
    end
    
    
    class Person
      include Utils
      include Logs
    end
    
    person = Person.new
    person.sayHello
    person.log

     

    if We extend the modules in Person call the methods will be available as class methods.

    class Person
      extend Utils
      extend Logs
    end
    
    
    Person.sayHello
    Person.log

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: