How fanriff.com works, Part I

I thought I’d write about how fanriff.com serves its Ember.js index from its Sinatra.rb API, and how web clients interacts with the back-end once the application is loaded. It started to run a little long so I’ve broken it up into parts. This first chapter will cover some background information on Ember, the fanriff.com web architecture, and how we deploy our Ember index to our stack.

Continue reading

Rack::Deflater in Sinatra

“Can I use Rack::Deflater in my Sinatra application?” Yes, absolutely. It’s a piece of Rack middleware and therefore super easy to use:

use Rack::Deflater

Furthermore, the RubyDoc for Rack::Deflater gives a cool little example of how to conditionally enable Rack::Deflater based on the size of the response body:

use Rack::Deflater, :if => lambda {
  |env, status, headers, body| body.length > 512
}

Unfortunately, this doesn’t work in Sinatra, or at least not on Sinatra 1.4.6, Rack 1.6.4, and Ruby 2.2.3. Why? Well, body is (for some reason) an array, so its length is probably zero (nil body) or one. It also occurs to me that we care more about the byte size of the body than its string length; if you think a 513-byte response is worth compressing, 512 characters encoded in UTF-32 (2,048 bytes) certainly is!

Here’s a modified (and code-golfed) version of the above snippet for Sinatra:

use Rack::Deflater, :if => lambda {
  |*, body| body.map(&:bytesize).reduce(0, :+) > 512
}

Happy deflating!