Fine grain caching in rails using Memcache

by tokumine

speed up with memcache

Speed is pretty important, especially with searching. Fortunately it’s a cinch to use ultra fine grained caching in Rails (objects, search results, json data etc), as long as you’ve have installed the Memcache server, set it up, and started it. In your environments.rb:

Shake

require "memcache"
CACHE = MemCache.new('127.0.0.1')

In your application_controlller.rb:

private
def cache(key)
    begin
      unless output = CACHE.get(key)
        output = yield
        CACHE.set(key, output)
      end
      return output
    rescue MemCache::MemCacheError
      yield
    end
  end

Bake

With these simple methods, you’ll be able to cache anything you want simply by using:

output = cache(your_key) { YourClass.do_a_massive_query() }

If it’s not cached, the query will be run and stored in the cache for next time. If it is, you get your results back ultra fast. Another cool thing is that if you don’t have memcache installed (eg on your dev box), it will just default to doing the code in your block.

Advertisements