How to enable compression in Ruby on Rails?

Darkmouse picture Darkmouse · Aug 29, 2014 · Viewed 18.4k times · Source

I posted a similar question here

Serving Compressed Assets in Heroku with Rack-Zippy

but decided to give up on that service, since I couldn't get it to work.

I ran PageSpeed Insights on my website to determine the speed of my website.

The most important suggestion I received was to Enable Compression.

Compressing resources with gzip or deflate can reduce the number of bytes sent over the network.
Enable compression for the following resources to reduce their transfer size by 191.2KiB 
(74% reduction).

I've followed the instructions on this website

https://developers.google.com/speed/docs/insights/EnableCompression

and it says to consult the documentation for your web server on how to enable compression:

I've used this website to find out my web server

http://browserspy.dk/webserver.php

It turns out that my web server is WEBrick.

The PageSpeed Insights Page only lists the following 3 servers

Apache: Use mod_deflate
Nginx: Use ngx_http_gzip_module
IIS: Configure HTTP Compression

I've searched for documentation on gzip compression for WEBrick servers but couldn't find anything.

I've searched for how to enable compression in Rails and couldn't find anything. That's why I'm asking here.

I've tried using Rack Zippy but gave up on it.

Right now, I don't even know where to begin. My first step, is finding out what I should do.

Edit

I followed Ahmed's suggestion of using Rack::Deflator

I confirmed that I had it by running

rake middleware
=> use Rack::Deflator

and then

git add .
git commit -m '-'
git push heroku master

Unfortunately PageSpeed still says it needs to be compress. I confirmed that by going into Developer Tools << Network Settings and refreshing the page. Size and content were virtually identical for every resource meaning the files are not compressed.

Is there something wrong with one of my files?

Thank you for your help.

Here is my full config/application.rb file

require File.expand_path('../boot', __FILE__)

require 'rails/all'

Bundler.require(*Rails.groups)

module AppName
  class Application < Rails::Application

    config.middleware.use Rack::Deflater
    config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
    config.exceptions_app = self.routes

    config.cache_store = :memory_store

  end
end

If there is a problem, the source is likely over there, right?

Do I need to install the deflator gem?

Answer

Ahmed picture Ahmed · Aug 29, 2014

Enable compression

Add it to config/application.rb:

module YourApp
  class Application < Rails::Application
    config.middleware.use Rack::Deflater
  end
end

Source: http://robots.thoughtbot.com/content-compression-with-rack-deflater