Skip to content

Instantly share code, notes, and snippets.

@btucker
Created March 26, 2010 19:25
Show Gist options
  • Save btucker/345277 to your computer and use it in GitHub Desktop.
Save btucker/345277 to your computer and use it in GitHub Desktop.
Memcached action caching for Sinatra (doesn't work in sinatra >= 1.0)
# Adds support for passing a :cache parameter to action definitions, eg:
#
# get '/state_map/?', :cache => 'state_map' do
# ...
# end
#
# :cache can also simply be passed true, in which case the route definition is used as the base
# key name. In all cases, any params are also included in the key.
#
# Author: ben tucker <ben@btucker.net>
# Based on code from: http://railsillustrated.com/blazing-fast-sinatra-with-memcached.html
# Requires: http://github.com/gioext/sinatra-memcache
require 'sinatra/memcache'
require 'digest/md5'
module CacheableRoute
def self.included(base)
base.extend ClassMethods
base.class_eval do
class << self
alias_method :route_without_caching, :route unless method_defined?(:route_without_caching)
alias_method :route, :route_with_caching
end
end
end
module ClassMethods
def route_with_caching(verb, path, options={}, &block)
if cache_key = options.delete(:cache)
cache_key = path if cache_key === true
def wrap_block(key,block)
Proc.new do
cache("#{key}/#{params.to_a.sort.join("/")}") { instance_eval(&block) }
end
end
block = wrap_block(cache_key, block)
end
route_without_caching(verb, path, options, &block)
end
end
end
class Sinatra::Base
include CacheableRoute
end
@chirantan
Copy link

This works like a charm for me on stand-alone sinatra application. But when I try to Rack it up, I get the following error

undefined method `cache' for #WhateverApp:0xb71b9d6c

* file: cache.rb
* location: GET /categories
* line: 33

Apparently, it doesn't find the method "cache" under Sinatra::MemCache::Helpers. How do I fix this?

@btucker
Copy link
Author

btucker commented Aug 9, 2010

Yeah, I think this stopped working around Sinatra 1.0 (could be wrong) We ended up abandoning the approach and just using the cache method directly in each action. Not as pretty, but it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment