Created
August 23, 2010 09:58
-
-
Save potomak/545169 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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