Enabling browser caching of static content in Mongrel
This post describes a simple snippet you can include in your rails environment to enable caching of static content served up from Rails via Mongrel in a development environment.
By design, Mongrel doesn't include configuration options for caching headers on static content. Mongrel is optimized for dynamic content, and in a production deployments another web server such as Apache is used to render static content.
However, in a development environment, the lack of static content caching can be an issue for pages with large numbers of images, scripts, and stylesheets. Waiting to fetch all of these resources on every page request makes iterative development feel sluggish and doesn't accurately reflect what will occur in production.
The class used in Mongrel to serve static content is called DirHandler. By adding the following lines to your environment.rb file, you can extend DirHandler to set the Expires and Cache-Control headers so that all static content lives 10 years. As long as you refer to that content using the Rails helpers like "image_tag", timestamps will be appending to the URLs so that new versions of these assets will be correctly loaded whenever you update the files.
-
if defined? Mongrel::DirHandler
-
module Mongrel
-
class DirHandler
-
def send_file_with_expires(req_path, request, response, header_only=false)
-
response.header['Cache-Control'] = 'max-age=315360000'
-
response.header['Expires'] = (Time.now + 10.years).rfc2822
-
send_file_without_expires(req_path, request, response, header_only)
-
end
-
alias_method :send_file_without_expires, :send_file
-
alias_method :send_file, :send_file_with_expires
-
end
-
end
-
end