nebulab / erb-formatter

Format ERB files with speed and precision
MIT License
135 stars 22 forks source link

Don't format contents of `javascript_tag` method. #32

Open olbrich opened 10 months ago

olbrich commented 10 months ago

In normal usage of javascript_tag, the contents of the block are javascript, and not HTML. erb-formatter attempts to format these contents, which can mangle whitespace and make inline scripts hard to read. Something like...

<%= javascript_tag(nonce: true) do %>
// We're setting this directly here to help prevent Flash of Unstyled Content (FOUC).
class Showcase {
  static start() {
    const preference = window.matchMedia("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
    this.colorScheme = localStorage.colorScheme || preference;
  }

  static set colorScheme(value) {
    localStorage.colorScheme = value;
    document.documentElement.classList.toggle("sc-dark", value === "dark");
  }
}

Showcase.start();
<% end %>

becomes

<%= javascript_tag(nonce: true) do %>
// We're setting this directly here to help prevent Flash of Unstyled Content
(FOUC). class Showcase { static start() { const preference =
window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
this.colorScheme = localStorage.colorScheme || preference; } static set
colorScheme(value) { localStorage.colorScheme = value;
document.documentElement.classList.toggle("sc-dark", value === "dark"); } }
Showcase.start();
<% end %>

Note that it mangles the comment and results in malformed code in addition to making it difficult to read.

To complicate things, it is valid to include erb tags within the block. Ideally those tags should still be formatted.

This may apply to other helpers as well.

elia commented 9 months ago

Oh good call, I guess we should have some generic way to tell it to ignore the contents of a block or tag 🤔