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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 483
    Comment on it

    Module is one of the most important tool in the Ruby toolbox. They are generally used to namespace ruby classes.

    module Test
      class Hello
      end
    end

    The class Hello will be wrapped in the Test namespace which means that if we want to create an instance of the Hello class , we can prefix it with the namespace and two colons.

    a = Test::Hello.new
    

    We generally provide namespace to classes to avoid collisions between them. If i write a library with a certain class and you use my library in your class which already has a class with the same name as that of mine , then the definitions of both the classes will merge into one class , usually causing unexpected behaviour.

    # In testing/assetbase.rb
    module Testing
      class AssetBase < ActiveRecord::Base
      end
    end
    
    # In testing/textbase.rb
    module Testing
      class TextBase < ActiveRecord::Base
      end
    end
    
    # Used in a controller:
    asset = Testing::AssetBase.new
    text = Testing::TextBase.new

     

    It will be stored in a subfolder of models with the name of the namespace, so here app/models/testing/*.rb

 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: