Skip to content

Instantly share code, notes, and snippets.

@ryanbriones
Forked from antirez/sinatra_redis_cache.rb
Created March 22, 2011 21:26
Show Gist options
  • Save ryanbriones/882111 to your computer and use it in GitHub Desktop.
Save ryanbriones/882111 to your computer and use it in GitHub Desktop.
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'
configure do
set :rediscache, Redis.new
end
helpers do
def rediscache
settings.rediscache
end
end
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
get '/foo/:username' do
@var = "Hello #{params[:username]}"
cache_url(10,true) {erb :index}
end
@technoweenie
Copy link

It's still a global. Wouldn't you want :threadsafe => true?

@ryanbriones
Copy link
Author

I like the fact that it looks more sinatra-like and does not use "ruby globals", at least externally. Personal preference. :)

I'm not cool enough to know where :threadsafe => true would go, but it sounds like you would want it on a production project.

@mattyoho
Copy link

You'd put :threadsafe => true in the call to Redis.new, i.e., Redis.new(:thread_safe => true). After 2.2.0 hits, thread safety will be the default. :-)

@ryanbriones
Copy link
Author

Thank you Matt Yoho. :)

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