Page Caching in Sinatra

280 views
Skip to first unread message

Jonas Nicklas

unread,
Nov 21, 2007, 3:24:39 PM11/21/07
to sina...@googlegroups.com
Hey there,

I've been using Sinatra a bit, and all I can say is, it rocks! So I've been hacking around a bit, and implemented a simple-as-dirt solution for page caching. You could then put Sinatra behin an Apache proxy and serve the static files via Apache, and serve the rest via Sinatra. Good stuff.

Here goes:

===================

require 'fileutils'

module Caching
  
  def cache(text)
   # requests to / should be cached as index.html 
   uri = request.env["REQUEST_URI"] == "/" ? 'index' : request.env["REQUEST_URI"]
   
   # Don't cache pages with query strings. 
   unless uri =~ /\?/
      uri << '.html'
      # put all cached files in a subdirectory called 'cache'
      path = File.join(File.dirname(__FILE__), 'cache', uri)

      # Create the directory if it doesn't exist
      FileUtils.mkdir_p(File.dirname(path))

      # Write the text passed to the path
      File.open(path, 'w') { |f| f.write( text ) }    
    end
    return text
  end

end

Sinatra::EventContext.send :include, Caching

# you can then use it like this:

get '/' do

  cache erb( :index, :layout => 'app.erb' )
 
end

===============

Kinda brute force, but it's simple and does the trick.

/Jonas

Blake Mizerany

unread,
Nov 21, 2007, 5:41:47 PM11/21/07
to sina...@googlegroups.com
KILLER! Thank you. I'll get this in the next release


--
Blake Mizerany
blake.m...@gmail.com

Reply all
Reply to author
Forward
0 new messages