Rails OutputCompressionFilter
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:
require 'stringio'
require 'zlib'
class OutputCompressionFilter
# Do output compression if the client supports it
def self.filter(controller)
if controller.request.env['HTTP_ACCEPT_ENCODING'].match(/gzip/)
if controller.response.headers["Content-Transfer-Encoding"] != 'binary'
begin
controller.logger.info "Compressing"
ostream = StringIO.new
gz = Zlib::GzipWriter.new(ostream)
gz.write(controller.response.body)
controller.response.body = ostream.string
controller.response.headers['Content-Encoding'] = 'gzip'
ensure
gz.close if gz
end
end
end
end
endHere is the source file – put it in your lib directory.
Here is how you use this code:
require "compress.rb"
class ApplicationController < ActionController::Base
after_filter OutputCompressionFilter
...
endThis 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.
Trackbacks
Use the following link to trackback from your own site:
http://blog.craz8.com/trackbacks?article_id=rails-outputcompressionfilter&day=17&month=12&year=2005
[...] Having it turned on in Apache is ideal because then it’ll affect static content as well, but there are ways to do it in Rails (and probably other languages, but I only care about Rails). Courtesy Tom Fakes, here are short and sweet instructions. [...]