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

Debugging Rails

Posted by Darshan Patil Sat, 22 Sep 2007 19:40:00 GMT

script/breakpointer does not work anymore with the latest stable version of rails. The new way to debug rails applications is to use ruby-debug. To use this to debug your rails applications, do the following

gem install ruby-debug

Once, that is done, edit config/environments/development.rb in your rails application and add the following line to the end of the file.

require 'ruby-debug' 

To break into the debugger, you need to call

debugger()

where you would have previously called breakpoint(). When debugger() is executed, the server will break into the debugger. Run help to see a list of available commands. You can also launch an irb process by typing irb at the debugger prompt.

Note: Debugger does not work with fastcgi. It works with mongrel and webrick.

mysql.rb errors after upgrading ruby 7

Posted by Darshan Patil Thu, 09 Aug 2007 05:34:00 GMT

I just noticed that my rails projects broke after I upgraded ruby on my linux box. Projects that had gems and rails frozen break. This is because of code in the SHA1 class not being backward compatible.

To quickly fix a broken rails app that shows the following error:
vendor/rails/activerecord/lib/active_record/vendor/mysql.rb:551:in `initialize'

edit the mysql.rb file so that the scramble41 routine looks like:

  def scramble41(password, message)
    return 0x00.chr if password.nil? or password.empty?
    buf = [0x14]
    s1 = Digest::SHA1.digest(password)
    s2 = Digest::SHA1.digest(s1)
    x = Digest::SHA1.digest(message + s2)
    (0..s1.length - 1).each {|i| buf.push(s1[i] ^ x[i])}
    buf.pack("C*")
  end

Older posts: 1 2 3 ... 12