Middleman + rack-zippy is a gzipped peanut butter cup

You got peanut butter in my chocolate!

You got chocolate in my peanut butter!

You got…gzip in my browser?

This site is built in Middleman, an excellent static-site blogging engine. When you run middleman build, Middleman generates gzipped files for you: index.html.gz and index.html. Recently I realized that I wasn’t getting the benefit of that gzipping — my Rack configuration wasn’t doing anything with the gzipped files.

Enter rack-zippy.

rack-zippy smartly finds and serve gzipped files, then falls back to non-gzipped files. It tries to find files in the following order:

To handle 404s, I created a tiny Rack app to serve a custom 404 page if rack-zippy doesn’t find anything. Here’s my config.ru:

# config.ru

# Look for files in ./build
use Rack::Zippy::AssetServer, "./build"

# Serve 404 messages if we get past Rack::Zippy
four_oh_four_app = lambda do |env|
  not_found_page = File.read("./build/404/index.html")

  [404, {"Content-Type" => "text/html"}, [not_found_page]]

run four_oh_four_app

I have some XML and JSON files on this site, which rack-zippy doesn’t pick up by default. I put this at the top of the config.ru to tell it to look for those too:

Rack::Zippy.configure do |config|
  config.static_extensions.push("xml", "json")

Now this site takes full advantage of Middleman’s gzipping, while still falling back to non-gzipped files for browsers that don’t support it, and serving my custom 404. Nice.

Middleman + rack-zippy: a delicious (but skinny) peanut butter cup.