SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

Roll Your Own Full Page Caching in Sinatra

       

It's as simple as this.


# app.rb
get '/:slug' do
  @slug   = File.basename("#{params[:slug]}")
  @cache = "public/cache/#{@slug}.html"

  if File.exists?(@cache)
    File.read(@cache)
  else
    @post = Post.find_by(page: params[:slug])
    html = erb(:post)
    File.write(@cache, html)
    html
  end
end

Use File.basename to make sure that params[:page] doesn't contain path information. This way arbitrary requests aren't able to traverse the filesystem. Then just check to see if the file exists. If it does read and return it. Otherwise, got to the database, compile the template, write to disk and serve!

You will need to expire the cache if the resource changes. The simple approach is to add a callback to your model that removes the cache. You could also put this logic in the controller.


class Post < ActiveRecord::Base
  after_save do
    FileUtils.rm("public/cache/#{slug}.html") if File.exists?("public/cache/#{slug}.html")
  end
end

There are a number of Gems for caching that are worth a look if you need something a little more robust. But this is a good start.

Tagged w/ #sinatra #caching #diy

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app