scattrbrain
Darshan Patil's personal blog
Super fast cache for webservice clients in Ruby 2
I implemented a cache on my website for the AllPosters.com webservice. Instead of caching the raw response from the webservice, I cache the model constructed after parsing the results. The speedup I get on a cache hit is ridiculous because I don’t need to parse data anymore.
My secret weapon was YAML. All I do is take the model constructed after parsing the data and call to_yaml on it. On a cache hit, I simply call YAML::load. Here is the code. Let me know if this can be improved.
require 'digest/sha1'
require 'yaml'
module Utils
class Cache
@@cache_dir = "./cache/"
def self.write(keywords, data)
File.open(@@cache_dir + digest(keywords), "w") { |f| f.write(data.to_yaml) }
end
def self.cached?(keywords)
File.exists?(@@cache_dir + digest(keywords))
end
def self.read(keywords)
YAML::load(File.open(@@cache_dir + digest(keywords)))
end
def self.expire(keywords)
File.delete(digest(keywords))
end
private
@@lookup = {}
def self.digest(keywords)
@@lookup[keywords] ||= Digest::SHA1.hexdigest(keywords)
end
end
end













