Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gzip assets in Sinatra app

I have been reading that zipping your assets using gzip will increase the performance of a site. There seems to be many ways to do this in a Sinatra application, so i was looking to confirm the most effective and easiest way to understand.

I have come across

use Rack::Deflater

Which should be placed in my config.ru file before running the app, so in my case

require './david'
use Rack::Deflater
run Sinatra::Application

is that it? is it this simple, Just to add I know this will zip all my static assets, including my images, but these are served from a CDN so would that make a difference?

Ant help appreciated with this one

Thanks

like image 934
Richlewis Avatar asked May 29 '13 11:05

Richlewis


1 Answers

It is that easy (isn't that nice:) but if you want to check, then look at the Content-Encoding response header and it should say gzip. In a webkit browser it's in the developer tools under "Network", then select the resource, like app.min.css and the "Headers" tab.

A way to test for this is given in the following blog post:

http://artsy.github.io/blog/2012/02/24/10x-rack-and-rails-output-compression-with-rack-deflater/

I modified the specs into shared examples, so I can add them in where I really want to check:

shared_examples "Compressed pages" do
  subject { last_response.headers }
  its(["Content-Encoding"]) { should be_nil }
  context "After compression" do
    before do
      get page
      @etag = last_response.headers["Etag"]
      @content_length = last_response.headers["Content-Length"]
      get page, {}, { "HTTP_ACCEPT_ENCODING" => "gzip" }
    end
    its(["Etag"]) { should == @etag }
    its(["Content-Length"]) { should_not == @content_length }
    its(["Content-Encoding"]) { should == "gzip"}
  end
end

My main spec uses it like this:

  describe "Public pages" do

    describe "Home page", :type => :request do
      let(:page) { "/" }
      it_behaves_like "Compressed pages"

The it_behaves_like "Compressed pages" will run that shared example and check it has the right header etc.

like image 169
ian Avatar answered Oct 24 '22 11:10

ian