Skip to content

Instantly share code, notes, and snippets.

@potomak
Created August 23, 2010 09:58
Show Gist options
  • Save potomak/545169 to your computer and use it in GitHub Desktop.
Save potomak/545169 to your computer and use it in GitHub Desktop.
# A simple expiring cache suitable for use with the PStore store.
#
# Usage:
# SimpleCache.fetch('my_data', 15.minutes) do
# MyModel.expensive_query
# end
#
require 'pstore'
module SimpleCache
CACHE_FILE = "#{Rails.root}/tmp/simple_cache"
# 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)
store = PStore.new(CACHE_FILE)
data = nil
store.transaction do
data = store[cache_key]
end
if !data || data[:inserted_at] < expires_in.ago.utc
value = yield
store.transaction do
store[cache_key] = {
:inserted_at => Time.now.utc,
:value => value
}
end
return value
else
return data[:value]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment