Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Created June 5, 2016 22:43
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 anonymous/35cf4eb4e2f64e6f42a1a7ccbafcd248 to your computer and use it in GitHub Desktop.
Save anonymous/35cf4eb4e2f64e6f42a1a7ccbafcd248 to your computer and use it in GitHub Desktop.
class HtmlMinifier
def initialize(app)
@app = app
end
def call(env)
# Call the underlying application, return a standard Rack response
status, headers, response = @app.call(env)
# Make sure we don't process linked CSS or JS
if headers["Content-Type"] =~ /text\/html/
response.each do |chunk|
[
# Join lines
[/[\r\n]+/, ""],
# Remove whitespace between tags
[/>\s+</, "><"],
# Remove comments
[/<!--(.|\s)*?-->/, ""],
# Remove whitespace in inline JavaScript
[/;\s+/, ";"],
[/{\s+/, "{"]
].each do |regex, substitute|
chunk.gsub! regex, substitute
end
end
end
# Return the new Rack response
[status, headers, response]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment