Saturday, December 3, 2011

Caching in Rails

Rails has wonderful inbuilt caching methods. This is how i implemented caching for a particular action. 

 Requirement : Cache a page for 12 hours. After 12 hrs Caching must expire.

  before_filter :clear_cache
  caches_action :index, :layout => false

def index  
    # Write expiry time to cache (12 hours)
    Rails.cache.write('expiry_time', + 12.hours)

def clear_cache
    #Fetch time from cache and check with current time
    t = Rails.cache.fetch('expiry_time') ||
    t = Time.parse(t) if t.is_a?(String)
    # Expire action if current time > Cached time
    expire_action :action => :index if > t