Adds a very simple Page Caching functionality to Sinatra
This is unfinished work, so use with care.
If you find it lacking or badly coded, please feel free to fork and improve. I’ll be very happy :)
= Make caching an option of the normal erb()/haml()/sass() methods, sort of like this:
erb(:index, :cache => true/false)
- alternatively enable caching by setting a global config like this
set :cache_enabled_for :all || :only/except => [‘/’,‘/contact’,…]
= Improve the logging output to the standard Sinatra output (if we are having :logging enabled )
= Add fragment caching…
= Enable the options functionality for the :cache & :cache_expire methods, so that they can take custom extensions and more
Example 1: Sinatra ‘classic’ app.
require ‘sinatra/cache’
- toggle for the cache functionality.
set :cache_enabled, true- sets the default extension for cached files
set :cache_page_extension, ‘.html’sets the Cache dir to the root of the /public directory.
set :cache_output_dir, ’’ # was :cache_dir
…
Example 2: Sinatra ‘sub-classed’ app.
<snip....>
require 'sinatra/cache'
class MyApp < Sinatra::Base
register Sinatra::Cache
# toggle for the cache functionality.
set :cache_enabled, true
# sets the default extension for cached files
set :cache_page_extension, '.html'
# sets the Cache output dir to the root of the /public directory.
set :cache_output_dir, '' # was :cache_dir
<snip....>
Basic Page Caching into static HTML files
get '/contact' do
# NB! options is currently not working
cache( erb( :contact ), :options => 'should go here' )
end
Expiring old pages (ie: after POST or PUT events)
# not very good example
post '/contact' do
cache_expire( '/contact', options )
end
See the test and test/fixtures directories for more examples.
- :cache_enabled => toggle for the cache functionality. Default is: true
- :cache_page_extension => sets the default extension for cached files. Default is: .html
- :cache_output_dir => sets cache directory where cached files are stored. Default is: ‘’(empty) == root of /public.
set to empty, since the ideal ’system/cache/’ does not currently work with Passenger & mod_rewrite :( - :cache_logging => toggle for logging the cache calls. Default is: true
- :cache_logging_level => sets the level of the cache logger. Default is: :info.
Options:(unused atm) [:info, :warn, :debug]
A big Thank You! goes to rtomayko, blakemizerany and others working on the Sinatra framework.
Inspired by code from Rails & Merb
and sinatra-mailer