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

(Tuis.) #1
Architectural Scalability | 177

Page caching


Page cachingis conceptually the simplest form of response caching, and it is also the
fastest method. However, it is also the least flexible as it caches an entire page. When
a page is cached, on first access Rails stores the entire HTML response in a file whose
name corresponds to the path used to access the action. For example, the cached
response to the path /people/show/12would be stored in RAILS_ROOT/public/
people/show/12.html. This enables the web server to answer subsequent requests
directly from the file instead of consulting Rails.*


Because the entire page is cached and served from the filesystem, page caching can-
not be used if even a small part of the page is dynamic. But it is this same characteris-
tic that makes page caching incredibly fast. Page caching is activated with the
caches_page class method:


class PersonController < ActionController::Base
caches_page :list, :show, :new
end

Once a page is cached in the filesystem, it must be manually removed if the informa-
tion becomes stale. Rails has a method,expire_page, which removes the specified
page from the page cache. It is not recommended to expire pages directly from the
controller, as you must remember to expire at any point where you update the
related models. This gets ugly, and it is way too brittle when code changes. Even
though caching is a controller-related function, cache expiration is much more of a
model-related concern.


Far better is to usecache sweepers, which are model observers that expire the appro-
priate pages when the related model objects change. The sweepers callexpire_page
as needed. We will cover sweepers later in this chapter.


Do not use page caching if the output depends on any query string parameters. If you
do, the page will be cached with the parameters passed to the first request, and subse-
quent requests will ignore the parameters as they are served from the filesystem.


If you use page caching, be sure that your generated URLs do not end with a trailing
slash (/controller/action/id/). The route recognizer will function properly in that case, but
page caching will be broken because the web server won’t find the appropriate file.


Action caching


Where page caching is too generic, there is another option:action caching. Action
caching still stores the entire HTML response, but it runs the filters first. This is very
useful if you have static pages that only authenticated users can see. Performance is
worse than page caching, as Rails must process each request.



  • When serving Rails applications, web servers are configured to first check the/publicdirectory for a file
    matching the request. If the file is not found, they pass the request to Rails.

Free download pdf