Created
February 17, 2009 09:50
-
-
Save toolmantim/65669 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
# Example simple stupid in-memory cache | |
class HashCache | |
def initialize(seconds_timeout) | |
@seconds_timeout = seconds_timeout | |
@cache = {} | |
end | |
def fetch(key, &block) | |
if @cache[key] && fresh?(@cache[key][:set_at]) | |
return @cache[key][:value] | |
else | |
value = yield | |
@cache[key] = {:value => value, :set_at => Time.now} | |
return value | |
end | |
end | |
def fresh?(set_at) | |
(set_at + @seconds_timeout) > Time.now | |
end | |
end | |
CACHE = HashCache.new(5) # 5 seconds | |
def fetch_photos(tags) | |
puts "Fetching photos for #{tags.inspect}" | |
CACHE.fetch(tags) { puts "Doing API call..."; sleep(1); ["photo.jpg"] } | |
end | |
tags = %w(lachlanhardy espresso martini) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
puts "No request for 8 seconds" | |
sleep(8) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) | |
fetch_photos(tags) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment