Skip to content

Instantly share code, notes, and snippets.

@craigp
Forked from mralex/sinatra-memcacher.rb
Created November 27, 2012 13:53
Show Gist options
  • Save craigp/4154316 to your computer and use it in GitHub Desktop.
Save craigp/4154316 to your computer and use it in GitHub Desktop.
Simple memcached helper for Sinatra.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment