Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

174 | Chapter 6: Performance


Nevertheless, there are a few other concerns that you should be aware of when scal-
ing a Rails application. The biggest concerns are the other shared state besides the
application data: storage for sessions and cached data.


Sessions


The Rails session infrastructure is built on top of Ruby’sCGI::Sessionfrom the stan-
dard library.*CGI::Sessiontakes care of the basics of CGI session management. It pro-
vides the following session stores, each implemented as a class withinCGI::Session:


FileStore
Stores data in a file as plain text. No attempt is made to marshal the data, so you
must convert any session data into aString first.


MemoryStore
Stores session data natively in the memory of the Ruby interpreter process.


PStore
Similar to FileStore, but marshals the data before storing it. This allows you to
store any type of data in the session. This is a good option for development, but
it is not suitable for a production environment.


Because these options are quite thin and not too suited for large-scale web applica-
tions, Rails provides some session managers that are more helpful. In particular, all
of these options enable sessions to be shared between different application servers.
These implement the same interface as the otherCGI::Sessionstores, so they are
drop-in replacements. We will examine each one in detail here.


ActiveRecordStore


As its name suggests, the ActiveRecordStore is designed to store sessions in a data-
base via ActiveRecord. However, it is flexible, and does not strictly require
ActiveRecord. The standard usage of ActiveRecordStore is very simple if you are
already using ActiveRecord—just set the session store inconfig/environment.rb:


config.action_controller.session_store = :active_record_store

A Rake task is provided to create the database migration for the sessions table:rake
db:sessions:create. You do not need to create the ActiveRecordSessionclass, as the
ActiveRecordStore sets one up for you. This class is called CGI::Session::
ActiveRecordStore::Session, so you can poke around its internals if you need to
change anything:


CGI::Session::ActiveRecordStore::Session.table_name = 'web_sessions'

The ActiveRecordStore uses few features of ActiveRecord, so it will actually work
with classes that act like ActiveRecord. This is useful if you are not otherwise using



  • Standard library documentation is available athttp://www.ruby-doc.org/stdlib/.

Free download pdf