Created
June 5, 2016 22:43
-
-
Save anonymous/35cf4eb4e2f64e6f42a1a7ccbafcd248 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
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