Handling Cookies and DHTML Effects with Ruby on Rails (Page 1 of 4 )
15.12 Setting and Retrieving Cookies
You want to set a cookie from within Rails.
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
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:
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.
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:*
Here are some other options for a cookie hash passed into cookies.
The domain to which this cookie applies:
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):
Whether this cookie is secure (secure cookies are only transmitted over HTTPS connections; the default is false):
Finally, Rails provides a quick and easy way to delete cookies:
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.
Recipe 3.5, "Doing Date Arithmetic"