Skip to content

Instantly share code, notes, and snippets.

@toolmantim
Created February 17, 2009 09:50
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 toolmantim/65669 to your computer and use it in GitHub Desktop.
Save toolmantim/65669 to your computer and use it in GitHub Desktop.
# 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