Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Handling Cookies and DHTML Effects with Ru...
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 
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

Handling Cookies and DHTML Effects with Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 6
    2007-04-12

    Table of Contents:
  • Handling Cookies and DHTML Effects with Ruby on Rails
  • 15.13 Extracting Code into Helper Functions
  • 15.14 Refactoring the View into Partial Snippets of Views
  • 15.15 Adding DHTML Effects with script.aculo.us

  • 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


    Handling Cookies and DHTML Effects with Ruby on Rails


    (Page 1 of 4 )

    In this fourth article of a six-part series covering web development and Ruby on Rails, you'll learn how to extract code into helper functions, add DHTML effects, and more. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    15.12 Setting and Retrieving Cookies

    Problem

    You want to set a cookie from within Rails.

    Solution

    Recall from Recipe 15.11 that all Rails controllers, views, helpers, and mailers have access to a method called sessions that returns a hash of the current client's session information. Your controllers, helpers, and mailers (but not your views) also have access to a method called cookies, which returns a hash of the current clients HTTP cookies.

    To set a cookie for a user, simply set a key/value pair in that hash. For example, to keep track of how many pages a visitor has looked at, you might set a "visits" cookie:

      class ApplicationController < ActionController::Base
        before_filter :count_visits

        private

        def count_visits
          value = (cookies[:visits] || '0').to_i
          cookies[:visits] = (value + 1).to_s
          @visits = cookies[:visits]
       
    end
      end

    The call to before_filter tells Rails to run this method before calling any action method. The private declaration makes sure that Rails doesn't think the count_visits method is itself an action method that the public can view.

    Since cookies are not directly available to views, count_visits makes the value of the :visits cookie available as the instance variable @visits. This variable can be accessed from a view:

      <!-- index.rhtml -->
      You've visited this website's pages <%= @visits %> time(s).

    HTTP cookie values can only be strings. Rails can automatically convert some values to strings, but it's safest to store only string values in cookies. If you need to store objects that can't easily be converted to and from strings, you should probably store them in the session hash instead.

    Discussion

    There may be times when you want more control over your cookies. For instance, Rails cookies expire by default when the user closes their browser session. If you want to change the browser expiration time, you can give cookies a hash that contains an :expires key and a time to expire the cookie. The following cookie will expire after one hour:*

      cookies[:user_id] = { :value => '123', :expires => Time.now + 1.hour}

    Here are some other options for a cookie hash passed into cookies.

    The domain to which this cookie applies:

      :domain

    The URL path to which this cookie applies (by default, the cookie applies to the entire domain: this means that if you host multiple applications on the same domain, their cookies may conflict):

      :path

    Whether this cookie is secure (secure cookies are only transmitted over HTTPS connections; the default is false):

      :secure

    Finally, Rails provides a quick and easy way to delete cookies:

      cookies.delete :user_id

    Of course, every Ruby hash implements a delete method, but the cookies hash is a little different. It includes special code so that not only does calling delete remove a key-value pair from the cookies hash, it removes the corresponding cookie from the user's browser.

    See Also

    1. Recipe 3.5, "Doing Date Arithmetic"
    2. Recipe 15.11, "Setting and Retrieving Session Information," has a discussion of when to use cookies and when to use session

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · 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-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek