One of the major weaknesses of the Rails cache file store is that cached pages cannot be expired by time. This poses a problem for keeping caching as simple as possible.
The solution I came up with stores cached content as a JSON file containing the content and the ttl.
Expiration needs only be set when @cache@ is called. @read_fragment@ should know nothing about expiration.
<% cache('home_most_popular', :expires_in=>1.day)do%>
<%= render :partial =>'most_popular'%><% end %>
The code that makes this work should go in @lib/hash_file_store.rb@
require'json'classHashFileStore<ActiveSupport::Cache::FileStoredefwrite(name,value,options=nil)ttl=0ifoptions.is_a?(Hash)&&options.has_key?(:expires_in)ttl=options[:expires_in]#options.delete(:expires_in) endvalue=JSON.generate({'ttl'=>ttl,'value'=>value.dup})superenddefread(name,options=nil)value=superreturnunlessvalue#malformed JSON is the same as no JSONvalue=JSON.parse(value)rescuenilfn=real_file_path(name)ifvalue&&(value['ttl']==0||(File.mtime(fn)>(Time.now-value['ttl'])))value['value']elsenilendendend
Put the following line in @config/environment.rb@ and it should be good to go.