Read more

Haml: Prevent whitespace from being stripped in production

Daniel Straßner
March 14, 2017Software engineer at makandra GmbH

Disclaimer

This is not an issue in newer versions of HAML (starting with 5.0.0), as the ugly-option was removed Show archive.org snapshot so that in development everything is rendered ugly, too.

Problem

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

When HTML is rendered from HAML in production or staging environment, whitespace is removed to reduce the download size of the resulting pages. Therefore it might happen that whitespace you see in development is missing in production or staging.

Here is an example of two inlined bootstrap buttons in a table:

%td
  = link_to edit_admin_user_path(membership.user_id), class: 'btn' do
    Edit
  = link_to admin_membership_path(membership), method: :delete, class: 'btn' do
    Delete

In development you will see a small space between the buttons. In staging however, there is no space between the buttons.

Solution

To fix this, you could simply add an empty line after "Edit". Unfortunately this doesn't stop another developer from removing the empty line.
Instead it would be a good idea to create a helper method in application_helper.rb to make the intended whitespace more explicit:

def space
  # prevent haml whitespace being stripped in staging and production
  # which would lead to elements being stuck together.
  # As in development whitespace is not stripped, it looks good in
  # development even without this helper.
  ' '
end

Then you can add the space to your HAML file:

%td
  = link_to edit_admin_user_path(membership.user_id), class: 'btn' do
    Edit
  = space
  = link_to admin_membership_path(membership), method: :delete, class: 'btn' do
    Delete
Posted by Daniel Straßner to makandra dev (2017-03-14 15:51)