Login Systems and More with Ruby on Rails - 15.11 Setting and Retrieving Session Information (Page 4 of 4 )
You want to associate some data with each distinct web client that's using your application. The data needs to persist across HTTP requests.
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.
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:
A cookie can only store four kilobytes of data.
A cookie can only store a string value.
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:
The information is not sensitive and not very large.
You don't want to store session information about each visitor on your server.
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
Recipe 15.8, "Creating a Login System," has an example using flash
Recipe 15.12, "Setting and Retrieving Cookies"
Recipe 16.10, "Sharing a Hash Between Any Number of Computers"
Recipe 16.16, "Storing Data on Distributed RAM with MemCached"
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.