-
-
Save carloslopes/4337072 to your computer and use it in GitHub Desktop.
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 | |
Created byBryan 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__) | |
===================================================================================== | |
Usage changes | |
===================================================================================== | |
* define the :cache_path setting on your application (set :cache_path, File.join(settings.root, 'tmp/cache')) | |
<% fragment_cache :foobar, 60 do %> | |
... Stuff you want cached ... | |
<% end %> |
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' | |
module Sinatra | |
module FragmentCache | |
def fragment_cache(name, age, &block) | |
if cache = read_fragment(name, age) | |
@_out_buf << cache | |
else | |
pos = @_out_buf.length | |
tmp = block.call | |
write_fragment(name, tmp[pos..-1]) | |
end | |
end | |
private | |
def read_fragment(name, age) | |
cache_file = File.join(settings.cache_path, "#{name}.cache") | |
now = Time.now | |
if File.exist?(cache_file) | |
current_age = (now - File.mtime(cache_file)) / 60 | |
logger.info("Fragment for '#{name}' is #{current_age} minutes old.") | |
return false if current_age > age | |
return File.read(cache_file) | |
end | |
false | |
end | |
def write_fragment(name, buf) | |
cache_file = File.join(settings.cache_path, "#{name}.cache") | |
f = File.new(cache_file, 'w+') | |
f.write(buf) | |
f.close | |
logger.info("Fragment written for '#{name}'") | |
buf | |
end | |
end | |
helpers FragmentCache | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment