Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 4 - Login Systems and More with Ruby on Rails
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Login Systems and More with Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 11
    2007-04-05

    Table of Contents:
  • Login Systems and More with Ruby on Rails
  • 15.9 Storing Hashed User Passwords in the Database
  • 15.10 Escaping HTML and JavaScript for Display
  • 15.11 Setting and Retrieving Session Information

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Login Systems and More with Ruby on Rails - 15.11 Setting and Retrieving Session Information


    (Page 4 of 4 )

    Problem

    You want to associate some data with each distinct web client that's using your application. The data needs to persist across HTTP requests.

    Solution

    You can use cookies (see Recipe 15.12) but it's usually simpler to put the data in a user's session. Every visitor to your Rails site is automatically given a session cookie. Rails keys the value of the cookie to a hash of arbitrary data on the server.

    Throughout your entire Rails application, in controllers, views, helpers, and mailers, you can access this hash by calling a method called session. The objects stored in this hash are persisted across requests by the same web browser.

    This code in a controller tracks the time of a client's first visit to your web site:

      class IndexController < ApplicationController
        def index
          session[:first_time] ||= Time.now
        end
      end

    Within your view, you can write the following code to display the time:*

      <!-- index.rhtml -->
      You first visited this site on <%= session[:first_time] %>.

      That was <%= time_ago_in_words session[:first_time] %> ago.

    Discussion

    Cookies and sessions are very similar. They both store persistent data about a visitor to your site. They both let you implement stateful operations on top of HTTP, which has no state of its own. The main difference between cookies and sessions is that with cookies, all the data is stored on your visitors' computers in little cookie files. With sessions, all the data is stored on the web server. The client only keeps a small session cookie, which contains a unique ID that's tied to the data on the server. No personal data is ever stored on the visitor's computer.

    There are a number of reasons why you might want to use sessions instead of cookies:

    1. A cookie can only store four kilobytes of data.
    2. A cookie can only store a string value.
    3. If you store personal information in a cookie, it can be intercepted unless all of a client's requests are encrypted with SSL. Even then, cross-site scripting attacks may be able to read the client cookie and retrieve the sensitive information.

    On the other hand, cookies are useful when:

    1. The information is not sensitive and not very large.
    2. You don't want to store session information about each visitor on your server.
    3. You need speed from your application, and not every page needs to access the session data.

    Generally, it's a better idea to use sessions than to store data in cookies.

    You can include model objects in your session: this can save a lot of trouble over retrieving the same objects from the database on every request. However, if you are going to do this, it's a good idea to list in your application controller all the models you'll be putting into the session. This reduces the risk that Rails won't be able to deserialize the objects when retrieving them from the session store.

      class ApplicationController < ActionController::Base
        model :user, :ticket, :item, :history
      end

    Then you can put ActiveRecord objects into a session:

      class IndexController < ApplicationController
        def index
          session[:user] ||= User.find(params[:id])
        end
      end

    If your site doesn't need to store any information in sessions, you can disable the feature by adding the following code to your app/controllers/application.rb file:

      class ApplicationController < ActionController::Base
        session :off
      end

    As you may have guessed, you can also use the session method to turn sessions off for a single controller:

      class MyController < ApplicationController
        session :off
      end

    You can even bring it down to an action level:

      class MyController < ApplicationController
        session :off, :only => ['index']

        def index
          #This action will not have any sessions available to it
        end
      end

    The session interface is intended for data that persists over many actions, possibly over the user's entire visit to the site. If you just need to pass an object (like a status message) to the next action, it's simpler to use the flash construct described in Recipe 15.8:

      flash[:error] = 'Invalid login.'

    By default, Rails sessions are stored on the server via the PStore mechanism. This mechanism uses Marshal to serialize session data to temporary files. This approach works well for small sites, but if your site will be getting a lot of visitors or you need to run your Rails application concurrently on multiple servers, you should explore some of the alternatives.

    The three main alternatives are ActiveRecordStore, DRbStore, and MemCacheStore. ActiveRecordStore keeps session information in a database table: you can set up the table by running rake create_sessions_table on the command line. Both DRbStore and MemCacheStore create an in-memory hash that's accessible over the network, but they use different libraries.

    Ruby comes with a standard library called DRb that allows you to share objects (including hashes) over the network. Ruby also has a binding to the Memcached daemon, which has been used to help scale web sites like Slashdot and LiveJournal. Memcached works like a direct store into RAM, and can be distributed automatically over various computers without any special configuration.

    To change the session storing mechanism, edit your config/environment.rb file like this:

      Rails::Initializer.run do |config|
        config.action_controller.session_store = :active_record_store
      end

    See Also

    1. Recipe 15.8, "Creating a Login System," has an example using flash
    2. Recipe 15.12, "Setting and Retrieving Cookies"
    3. Recipe 16.10, "Sharing a Hash Between Any Number of Computers"
    4. Recipe 16.16, "Storing Data on Distributed RAM with MemCached" 
    5. http://wiki.rubyonrails.com/rails/pages/ HowtoChangeSessionOptions

    Please check back next week for the continuation of this article.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the "Ruby Cookbook," published by O'Reilly. We hope...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT