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  
    #code
    # Write expiry time to cache (12 hours)
    Rails.cache.write('expiry_time', Time.now + 12.hours)
end


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

Thanks!

No comments: