Created
May 5, 2011 05:41
-
-
Save mralex/956592 to your computer and use it in GitHub Desktop.
Simple memcached helper for Sinatra.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/base' | |
require 'memcached' | |
module Sinatra | |
module Memcacher | |
module Helpers | |
def cache(key, &block) | |
return block.call unless options.memcacher_enabled | |
begin | |
output = memcached.get(key) | |
rescue Memcached::NotFound | |
output = block.call | |
memcached.set(key, output, options.memcacher_expiry) | |
end | |
output | |
end | |
def expire(key) | |
begin | |
memcached.delete key | |
true | |
rescue Memcached::NotFound | |
false | |
end | |
end | |
private | |
def memcached | |
options.memcacher_client ||= Memcached.new(options.memcacher_server) | |
end | |
end | |
def self.registered(app) | |
app.helpers Memcacher::Helpers | |
app.set :memcacher_client, nil | |
app.set :memcacher_enabled, false | |
app.set :memcacher_server, "127.0.0.1:11211" | |
app.set :memcacher_expiry, 3600 | |
end | |
end | |
register Memcacher | |
end |
One word - Beautiful :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple memcached module, derived from gioext/sinatra-memcache, updated to use the 'memcached' gem.
Compatible with Sinatra 1.2
Usage
Activate in a modular Sinatra app:
Cache an action: