Skip to content

Instantly share code, notes, and snippets.

@parasew
Created January 28, 2011 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parasew/800443 to your computer and use it in GitHub Desktop.
Save parasew/800443 to your computer and use it in GitHub Desktop.
steamrolling: removing newlines and spaces from all html output (rack)
# 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