Created
November 15, 2009 07:05
-
-
Save techiferous/235068 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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