4 R4C81D
4 R4C81D

Reputation: 192

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.

Upvotes: 3

Views: 2190

Answers (2)

Robert Reiz
Robert Reiz

Reputation: 4442

There is a Gem for that. Just add this to your Gemfile:

gem 'htmlcompressor', '~> 0.4.0'

And this to your application.rb:

config.middleware.use HtmlCompressor::Rack

I'm using that within a Rails 6 application and it worked out of the box. I would also recommend to enable GZip compression. You can do that with this middleware:

config.middleware.use Rack::Deflater 

No external Gem needed for the last middleware.

Upvotes: 2

Mark Boulder
Mark Boulder

Reputation: 14307

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

Upvotes: 2

Related Questions