Amit Solanki

Avatar

A Ruby On Rails Programmer from India

Explicitly expiring timed_fragment_cache

One of the available plugins for time based fragment caching is timed_fragment_cache by Richard Livsey. A mirror for the plugin is available here at GitHub.

One of the limitation of the plugin is the inability to explicitly expire fragment cache, specifically in our sweeper. The method expire_fragment just clears the cache file but corresponding meta file which stores the time of expiration remains. You can add the following to your environment.rb to clear the meta file and explicitly expire cache in addition to automatic timed expiration feature offered by plugin.

module ActionController
  module Caching
    module TimedFragment
      def expire_meta_fragment(name)
        expire_fragment(meta_fragment_key(name))
      end
    end
  end
end

Now, in sweepers just call this new method along with expire_fragment method.

class ArticleSweeper < ActionController::Caching::Sweeper
  observe Article # This sweeper is going to keep an eye on the Article model

  # If our sweeper detects that an article was created call this
  def after_save(article)
    expire_cache_for(article)
  end

  # If our sweeper detects that an article was deleted call this
  def after_destroy(article)
    expire_cache_for(article)
  end

  private

  def expire_cache_for(record)
    # Expire the fragments now that we posted a new article entry
    expire_fragment({:controller => 'articles', :action => 'index'})
    expire_meta_fragment({:controller => 'articles', :action => 'index'})
  end
end

,

Before you go

Going so soon? May these links be a guide to web enlightenment.