Skip to content

Instantly share code, notes, and snippets.

@mralex
Created May 5, 2011 05:41
Show Gist options
  • Save mralex/956592 to your computer and use it in GitHub Desktop.
Save mralex/956592 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
@mralex
Copy link
Author

mralex commented May 5, 2011

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:

  register Sinatra::Memcacher
  set :memcacher_enabled, true
  set :memcacher_expiry, 86400 

Cache an action:

  get '/' do
    cache "index" do 
      @articles = Article.public.all(order: 'posted_at DESC', limit: 10)
      erb :index
    end
  end

@franciscodelgadodev
Copy link

One word - Beautiful :)

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