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!

Easy login sessions with Ember.js and Torii

This is an easy and simple session lifecycle solution pattern for Ember.js 1.13/2.0 using Torii 0.6.0 that I’d like to share. Ember is a framework for building single-page web applications (SPAs) in JavaScript and HTMLBars. Torii abstracts authentication (authn) and authorization (authz) services in Ember and gives you powerful hooks into authn providers (social media login, e.g. Facebook or Twitter, or your company’s internal directory service) and customizable authz adapters (i.e. your application’s backend). It can inject the session object returned by your API into routes and controllers, and protect routes that require authorization.

Continue reading