Skip to content

Instantly share code, notes, and snippets.

@bryanthompson
Created January 14, 2010 22:08
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bryanthompson/277560 to your computer and use it in GitHub Desktop.
Save bryanthompson/277560 to your computer and use it in GitHub Desktop.
Simple fragment caching in sinatra
Simple fragment caching helper for Sinatra
Bryan Thompson - bryan@radiowebservices.com - twitter.com/bryanthompson
Helper structure can probably be simplified, but I'm leaving space
for future improvements like memcache and other settings that I
might be overlooking right now
Actual caching scheme strongly inspired by merb and rails caching
methods.
Usage:
* drop cache_helper in a lib/ dir and require it
* set CACHE_ROOT
<% cache "name_of_cache", :max_age => 60 do %>
... Stuff you want cached ...
<% end %>
For now, .cache files are dumped right into a tmp directory.
defined as CACHE_ROOT. I set mine in my site.rb file as
CACHE_ROOT = File.dirname(__FILE__)
require 'sinatra/base'
class CacheHelper
module Sinatra
module Helpers
def cache(name, options = {}, &block)
if cache = read_fragment(name, options)
@_out_buf << cache
else
pos = @_out_buf.length
tmp = block.call
write_fragment(name, tmp[pos..-1], options)
end
end
def read_fragment(name, options = {})
cache_file = "#{CACHE_ROOT}/tmp/#{name}.cache"
now = Time.now
if File.file?(cache_file)
if options[:max_age]
(current_age = (now - File.mtime(cache_file)).to_i / 60)
puts "Fragment for '#{name}' is #{current_age} minutes old."
return false if (current_age > options[:max_age])
end
return File.read(cache_file)
end
false
end
def write_fragment(name, buf, options = {})
cache_file = "#{SINATRA_ROOT}/tmp/#{name}.cache"
f = File.new(cache_file, "w+")
f.write(buf)
f.close
puts "Fragment written for '#{name}'"
buf
end
end
def self.registered(app)
app.helpers CacheHelper::Sinatra::Helpers
end
end
end
Sinatra.register CacheHelper::Sinatra
@alfanick
Copy link

Thanks for inspiration. Couldn't make it working with Haml, but I made my own cache helper (specially for Haml) - https://gist.github.com/3742161

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