Three common forms of cachingThere are 3 types of caching that are very commonly talked about in the rails community; page caching, action caching, and fragment caching. All of these are well documented and are great ways to cache varying amounts of content for your pages.
Is that all the caching I need?Caching at the view level is great but it isn't necessarily the best fit for every situation. In some cases it may be easier to cache data at a lower level. Perhaps you want to cache the results of an external data request for a given period of time. None of the view caching methods would be a really great fit.
Lower level data cachingRails 3 actually has a great method for caching data at a lower level than the view. It even uses the same caching store as action and fragment caching. ActiveSupport::Cache::Store allows you to store any serializable Ruby object. Rails even provides an already initialized cache store via Rails.cache.
Example usage and codeI used this on www.checkthesock.com to cache METAR queries. I was using current_metar a gem I built that pulls metar data from ADDS. I made a model called CachedMetar to return cached results to the rest of my application.
Code walk throughThis model basically returns the result of the block argument to
Rails.cache.fetchthe first time it is called. Any time it is called within the next 5 minutes it returns the value that was cached the first time. Everywhere I had previously been calling
CurrentMetar::Metar.get_metar("ICAO code")I switched to call
CachedMetar.metar("ICAO code")and that was all it took.