Skip to content

Instantly share code, notes, and snippets.

@techiferous
Created November 15, 2009 07:05
Show Gist options
  • Save techiferous/235068 to your computer and use it in GitHub Desktop.
Save techiferous/235068 to your computer and use it in GitHub Desktop.
require 'nokogiri'
module Rack
class Steamroller
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
@doc = nil
@request = Rack::Request.new(env)
status, @headers, @body = @app.call(env)
if html?
@body = doc.at_css("body").content
@body.gsub!(/\s+/, ' ')
update_content_length
end
[status, @headers, @body]
end
private
def html?
@headers["Content-Type"] && @headers["Content-Type"].include?("text/html")
end
def doc
@doc ||= Nokogiri::HTML(body_to_string)
end
def body_to_string
s = ""
@body.each { |x| s << x }
s
end
def update_content_length
@headers['Content-Length'] = Rack::Utils.bytesize(@body).to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment