Skip to content

Instantly share code, notes, and snippets.

@skorfmann
Created September 15, 2010 09:17
Show Gist options
  • Save skorfmann/580459 to your computer and use it in GitHub Desktop.
Save skorfmann/580459 to your computer and use it in GitHub Desktop.
begin
require 'tokyocabinet'
rescue LoadError
puts "You need the tokyocabinet gem"
exit
end
require 'md5'
require 'net/http'
class HttpCache
extend Forwardable
def_delegators :@store, :close, :size, :keys, :has_key?
include Singleton
def initialize
file = "http_cache.tch"
@store = ::TokyoCabinet::HDB::new
@store.open(file, ::TokyoCabinet::HDB::OWRITER | ::TokyoCabinet::HDB::OCREAT)
end
def get(url)
hashed_url = MD5.hexdigest(url)
if data = self[hashed_url]
data[:body]
else
response = Net::HTTP.get_response(URI.parse(url)).body.to_s
self[hashed_url] = {:body => response, :timestamp => Time.now.to_i}
response
end
end
def []=(key, value)
@store[key] = [Marshal.dump(value)].pack("m")
end
def delete(key)
value = self[key]
@store.delete(key)
value
end
def [](key)
if value = @store[key]
load_value(value)
end
end
def timeout(ttl = 604800)
each do |key, value|
if value[:timestamp].to_i < Time.now.to_i - ttl
puts "deleting #{key}"
delete(key)
end
end
end
def each
@store.each { |k, v| yield k, load_value(v) }
end
protected
def load_value(value)
Marshal.load(value.unpack("m")[0])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment