Mike Perham

On Ruby, software and the Internet

Adding multi-get support to Rails

June 13th, 2009 · No Comments

Memcache-client has the ability to fetch multiple keys in one request but Rails does not expose this functionality. It’s really easy to add it yourself though:

config/initializers/rails_patches.rb

Rails.cache.instance_eval <<-EOM
  def read_multi(*keys)
    @data.get_multi(*keys)
  end
EOM

Rails uses read/write for its API naming so we name the method read_multi rather than get_multi. Here’s a sample usage in script/console:

>> Rails.cache.write('a', 1)
>> Rails.cache.write('b', 2)
>> Rails.cache.write('c', 3)
>> Rails.cache.read_multi('a', 'b', 'c')
=> {"a"=>1, "b"=>2, "c"=>3}

Enjoy!

Tags: Rails

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment