Skip to content

Instantly share code, notes, and snippets.

@carloslopes
Forked from bryanthompson/cache_helper.rb
Created December 19, 2012 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carloslopes/4337072 to your computer and use it in GitHub Desktop.
Save carloslopes/4337072 to your computer and use it in GitHub Desktop.
Simple fragment caching helper for Sinatra
Created byBryan 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__)
=====================================================================================
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 %>
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