Using gzip compression in Sinatra with Ruby

Just to highlight 'Rack::Deflater' way as an 'answer' ->

As mentioned in the comment above, just put the compression in config.ru

use Rack::Deflater

thats pretty much it!


After zipping the file you would simply return the result and ensure to set the header Content-Encoding: gzip for the response. Google has a nice, little introduction to gzip compression and what you have to watch out for. Here is what you could do in Sinatra:

get '/whatever' do
  headers['Content-Encoding'] = 'gzip'
  StringIO.new.tap do |io|
    gz = Zlib::GzipWriter.new(io)
    begin
      gz.write(File.read('public/Assets/Styles/build.css'))
    ensure
      gz.close
    end
  end.string
end

One final word of caution, though. You should probably choose this approach only for content that you created on the fly or if you just want to use gzip compression in a few places.

If, however, your goal is to serve most or even all of your static resources with gzip compression enabled, then it will be a much better solution to rely on what is already supported by your web server instead of polluting your code with this detail. There's a good chance that you can enable gzip compression with some configuration settings. Here's an example of how it is done for nginx.

Another alternative would be to use the Rack::Deflater middleware.