Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Time Based Expiration Of Cache Fragments In Ruby On Rails (MemCacheStore And FileStore)

DZone's Guide to

Time Based Expiration Of Cache Fragments In Ruby On Rails (MemCacheStore And FileStore)

·
Free Resource
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, █)
    @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
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}