Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Created April 10, 2011 00:49
Show Gist options
  • Save dhrrgn/911939 to your computer and use it in GitHub Desktop.
Save dhrrgn/911939 to your computer and use it in GitHub Desktop.
Simple time based file caching
# Time based file caching
#
# This allows you too set a lifetime on File Based caches
# This is a modified version of a class I found here:
# http://blog.ubrio.us/ruby/ruby-rails/simple-rails-time-based-fragment-caching-with-file-store/
#
# - Save this file somewhere (e.g. lib/timed_file_store.rb)
# - Include it (e.g. in config/application.rb)
#
# Example Usage:
#
# Enable it in config/application.rb
# config.cache_store = ActiveSupport::Cache::TimedFileStore.new(File.join(::Rails.root, 'tmp', 'cache'))
#
# In your controller action:
# @report = Report.find(params[:id])
# unless fragment_exist?("report_#{@report.id}", :lifetime => 1.week)
# @report.run!
# end
#
# In your view
# <% cache("report_#{@report.id}") do %>
# <!-- output the report HTML and such -->
# <% end %>
module ActiveSupport
module Cache
class TimedFileStore < FileStore
def exist?(name, options = {})
delete_if_expired(name, options[:lifetime]) unless options.blank? or options[:lifetime].blank?
super
end
def read(name, options = {})
delete_if_expired(name, options[:lifetime]) unless options.blank? or options[:lifetime].blank?
super
end
protected
def delete_if_expired(name, lifetime = 0)
delete(name) if expired?(name, lifetime) rescue nil
end
# Checks if the Cache is expired
def expired?(name, lifetime = 0)
return false unless lifetime > 0
(Time.now - File.mtime(real_file_path(name))) >= lifetime
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment