DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Time Based Expiration Of Cache Fragments In Ruby On Rails (MemCacheStore And FileStore)
This allows to expire cached fragments by ttl. Example usage (in views):
<% cache("name", :ttl => 7.days) do %>
... some database-heavy stuff ...
<% end %>
Put the following in environment.rb or in lib/.
class ActionController::Caching::Fragments::MemCacheStore
def write(name, value, options=nil)
if options.is_a?(Hash) && options.has_key?(:ttl)
ttl = options[:ttl]
else
ttl = 0
end
@data.set(name, value, ttl)
end
end
module ActionView::Helpers::CacheHelper
def cache(name = {}, options = nil, &block)
@controller.cache_erb_fragment(block, name, options)
end
end
class ActionController::Caching::Fragments::UnthreadedFileStore
def read(name, options = nil)
if options.is_a?(Hash) && options.has_key?(:ttl)
ttl = options[:ttl]
else
ttl = 0
end
fn = real_file_path(name)
# if cache expired act as if file doesn't exist
return if ttl > 0 && File.exists?(fn) && (File.mtime(fn) < (Time.now - ttl))
File.open(fn, 'rb') { |f| f.read } rescue nil
end
end





