Skip to content

Instantly share code, notes, and snippets.

@bhollis
Created June 3, 2011 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhollis/1005772 to your computer and use it in GitHub Desktop.
Save bhollis/1005772 to your computer and use it in GitHub Desktop.
Simple Rails caching library
# A simple expiring cache suitable for use with the :file_store cache store.
# Not particularly threadsafe, and can duplicate work if there are multiple
# requests for stale data at the same time.
#
# Usage:
# SimpleCache.fetch('my_data', 15.minutes) do
# MyModel.expensive_query
# end
#
# Make sure to set up the cache to use :file store in your environment.rb,
# like this:
# config.cache_store = :file_store, "#{RAILS_ROOT}/tmp/cache"
module SimpleCache
# Choose a cache_key and expiration time (e.g. 15.minutes), and pass a
# block that returns the data you want to cache. The block will only be
# evaluated if the cache has expired.
def self.fetch(cache_key, expires_in)
data = Rails.cache.read(cache_key)
if !data || data[:inserted_at] < expires_in.ago.utc
value = yield
Rails.cache.write(cache_key, {
:inserted_at => Time.now.utc,
:data => value
})
return value
else
return data[:data]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment