Formatting Rails ERB in Zed with Herb


I am spoiled by auto-formatting my files. In the frontend ecosystem, you take this for granted. Everywhere else, you have to tweak things to make auto-format work properly.

I am sharing my attempt at trying to format Rails .erb files in Zed.

No surprise, it involves installing a local npm package for your project (you should avoid installing things globally whenever possible) called Herb Formatter.

Warning: The tool is in experimental preview still. Make sure to review your diffs before merging

Update settings in Zed for Rails

You can add these to .zed/settings.json for your Rails project to keep this in version control.

These are my settings for Rails projects that work in tandem with rubocop and related gems. But focussing on the ERB formatting you only need the highlighted part below.

.zed/settings.json
{
  "languages": {
    "Ruby": {
      // Use ruby-lsp as the primary language server and rubocop as the secondary.
      "language_servers": ["ruby-lsp", "rubocop", "!solargraph"],
      // Enable herb and ruby-lsp for *.html.erb files
      "format_on_save": "on",
      "formatter": {
        "external": {
          "command": "./bin/bundle",
          "arguments": ["rubocop", "--autocorrect"],
        },
      },
    },
    // Copy this part for the formatter!
    "HTML+ERB": {
      "language_servers": ["herb", "ruby-lsp"],
      "formatter": {
        "external": {
          "command": "pnpm",
          "arguments": ["run", "--silent", "herb:format"],
        },
      },
    },
  },
}

The above won’t work without installing npm dev dependencies i.e. @herb-tools/formatter with the correct scripts.

package.json
{
  "name": "atelier-iris",
  "private": "true",
  "scripts": {
    "herb:format": "herb-format",
    "herb:format:check": "herb-format --check"
  },
  "devDependencies": {
    "@herb-tools/formatter": "^0.8.10",
  }
}