Created
January 28, 2011 16:01
-
-
Save parasew/800443 to your computer and use it in GitHub Desktop.
steamrolling: removing newlines and spaces from all html output (rack)
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
# code via techiferous ( https://github.com/techiferous ) | |
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=doc.to_s | |
@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