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
endTrackbacks
Use the following link to trackback from your own site:
http://scattrbrain.com/articles/trackback/253















Happy holidays to you too. and a belated Christmas wishes..
Keep on blogging, we need you. I’ve got so much useful stuff from your blog and really value you opinion in this stuff.