Search code examples
htmlruby-on-railsoptimizationhamlminify

How i can minify the HTML output in ruby on rails?


I have a ruby on rails app, and i'm using HAML for HTML structure,

I'd like to minify/uglify the output "html", remove unnecessary whitespaces and new lines.

Something like this:

<div class='wrapper v2-header-wrapper' id='fix-content'><div class='header header-search' style='text-align: center !important;'><nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand-lg'><button class='navbar-toggler navbar-toggler-right' onclick='openNav()' type='button'><span class='navbar-toggler-icon'><i class='fa fa-bars'></i></span></button><a class='navbar-brand mobile pull-left' href='/'><i class='fa fa-search'></i>

Instead of this:

<div class='wrapper v2-header-wrapper' id='fix-content'>
<div class='header header-search' style='text-align: center !important;'>
<nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand- 
lg'>
<button class='navbar-toggler navbar-toggler-right' onclick='openNav()' 
type='button'>
<span class='navbar-toggler-icon'>
<i class='fa fa-bars'></i>
</span>
</button>
<a class='navbar-brand mobile pull-left' href='/'>
<i class='fa fa-search'></i>

Your help is highly appreciated, thanks in advance.


Solution

  • Have a go at this:

    app/middleware/html_minifier.rb

    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 CSS or JavaScript
        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