Created
June 3, 2011 02:43
-
-
Save bhollis/1005772 to your computer and use it in GitHub Desktop.
Simple Rails caching library
This file contains hidden or 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 :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