Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS