Created
January 14, 2010 22:08
-
-
Save bryanthompson/277560 to your computer and use it in GitHub Desktop.
Simple fragment caching in sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Simple fragment caching helper for Sinatra | |
Bryan Thompson - [email protected] - 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__) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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