Skip to content

Instantly share code, notes, and snippets.

@antirez
Created March 22, 2011 21:06
Show Gist options
  • Save antirez/882058 to your computer and use it in GitHub Desktop.
Save antirez/882058 to your computer and use it in GitHub Desktop.
the simplest Redis caching for Sinatra -- not even tested... consider this code just an hint
Username = <%= @var %>
<!DOCTYPE html>
<html>
<head>
<title>Sinatra Redis Cache Example</title>
</head>
<body>
<%= yield %>
</body>
</html>
# This is just an hint for a simple Redis caching "framework" using Sinatra
# A friend of mine asked for something like that, after checking the first two gems realized there was
# a lot of useless complexity (IMHO). That's the result.
#
# The use_cache parameter is useful if you want to cache only if the user is authenticated or
# something like that, so you can do cache_url(ttl,User.logged_in?, ...)
require 'rubygems'
require 'sinatra'
require 'redis'
def cache(tag,ttl,use_cache,block)
if !use_cache
return yield
end
page = $rediscache.get(tag)
return page if page
page = block.call
$rediscache.setex(tag,ttl,page)
return page
end
def cache_url(ttl=300,use_cache=true,&block)
cache("url:#{request.url}",ttl,use_cache,block)
end
# The following is an idea for fragment caching.
def cache_func(ttl=300,use_cache=true,&block)
cache("func:#{request.url}",ttl,use_cache,block)
end
# And for invalidation of course
def cache_func_invalidate(tag)
$rediscache.del("func:#{tag}")
end
before do
$rediscache = Redis.new
end
get '/foo/:username' do
@var = "Hello #{params[:username]}"
cache_url(10,true) {erb :index}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment