Skip to content

Instantly share code, notes, and snippets.

@adam12
Forked from havenwood/cache.rb
Created November 11, 2022 02:37
Show Gist options
  • Save adam12/7021df7964cc371b8a5aa128cea49f07 to your computer and use it in GitHub Desktop.
Save adam12/7021df7964cc371b8a5aa128cea49f07 to your computer and use it in GitHub Desktop.
Another example for xco on #ruby IRC
require_relative 'tuple_space'
class Cache
def initialize
@memory = TupleSpace.new(reaper_period_in_secs: 10, expires_in_secs: 60)
end
def get(request)
@memory[request]
end
def set(request, response)
@memory[request] = response
end
end
Typhoeus::Config.cache = Cache.new
Typhoeus.get("www.example.com").cached?
#=> false
Typhoeus.get("www.example.com").cached?
#=> true
##
# Wait 60-70 seconds...
Typhoeus.get("www.example.com").cached?
#=> false
require 'rinda/tuplespace'
class TupleSpace < Rinda::TupleSpace
# 600 seconds is ten minutes and 86,400 seconds is 3 hours
def initialize reaper_period_in_secs: 600, expires_in_secs: 10_800
@expires_in_secs = expires_in_secs
super reaper_period_in_secs
end
def []= key, value
take [key, nil], true
rescue Rinda::RequestExpiredError
nil
ensure
write [key, value], @expires_in_secs
end
def [] key
read([key, nil], true).last
rescue Rinda::RequestExpiredError
nil
end
def delete key
take([key, nil], true).last
rescue Rinda::RequestExpiredError
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment