Rails OutputCompressionFilter

December 17, 2005 Link to post  Permalink

The Rails documentation has passing references to a filter class called OutputCompressionFilter. However, this code is nowhere to be found.

Since I have some code to do output compression (see my earlier post), I decided to repackage it as this class:

 1equire 'stringio'
 2require 'zlib'
 3
 4class OutputCompressionFilter
 5
 6  # Do output compression if the client supports it
 7  def self.filter(controller)
 8    if controller.request.env['HTTP_ACCEPT_ENCODING'].match(/gzip/)
 9      if controller.response.headers["Content-Transfer-Encoding"] != 'binary'
10        begin
11          controller.logger.info "Compressing"
12          ostream = StringIO.new
13          gz = Zlib::GzipWriter.new(ostream)
14          gz.write(controller.response.body)
15          controller.response.body = ostream.string
16          controller.response.headers['Content-Encoding'] = 'gzip'
17        ensure
18          gz.close if gz
19        end
20      end
21    end
22  end
23  
24end

Here is the source file – put it in your lib directory.

Here is how you use this code:

1equire "compress.rb"
2
3class ApplicationController < ActionController::Base
4  after_filter OutputCompressionFilter
5  ...
6end

This code works just like the Rails Filter documentation indicates.

Update: I’ve updated the source file to include the major updates in the comments from Dan, and my updates to that code.