Sponsors

Super fast cache for webservice clients in Ruby 2

Posted by Darshan Patil Sat, 08 Dec 2007 06:36:00 GMT

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
Trackbacks

Use the following link to trackback from your own site:
http://scattrbrain.com/articles/trackback/253

Comments

Leave a response

  1. Nensi Wed, 02 Jan 2008 13:13:06 GMT

    Happy holidays to you too. and a belated Christmas wishes..

  2. Sagen Fri, 25 Jan 2008 11:57:48 GMT

    Keep on blogging, we need you. I’ve got so much useful stuff from your blog and really value you opinion in this stuff.

Comments