How to format .erb and .rb files in VSCode

Usecase

  • You have switched from another IDE and you have no idea how to set up VSCode just yet
  • You have to (just like myself) write some Ruby (Rails) at your work and your VSCode isn’t ready for that
  • You’ve tried everything and your .erb files are still not being formatted. You found this article, you have no hope but you will still copy/paste stuff I wrote and pray to the holy and unholy that it works

Prerequisites

How

For the impatient ones, simply copy the provided JSON into your own settings.json file. Of course, assuming that you have installed the stuff in the previous section.

  "files.associations": {
    "*.erb": "erb"
  },
  "[erb]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "aliariff.vscode-erb-beautify",
  },

In simple words, what can often happen in VSCode is that the default ruby formatter tries to (unsuccessfully) format the .erb files. Due to this conflict, ERB Formatter/Beautify fails to do the job.

Explanation

 "files.associations": {
    "*.erb": "erb"
  }

Ensures that files with extensions like e.g. foo.html.erb are also properly formatted.

 "[erb]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "aliariff.vscode-erb-beautify",
  }

Even though it’s self-explanatory, it ensures that files with the extension .erb are formatted on save and that the default formatter is ERB Formatter/Beautify. This is actually the most critical step, to ensure that rufo (Ruby formatter) is not causing the conflicts.

Emmet (optional and suggested)

If you are using Emmet, it won’t work in the .erb files by default.

To enable it, we have to associate the .erb file type with the HTML file type. This way, emmet will behave the same way as it behaves in the HTML files.

  "emmet.includeLanguages": {
    "erb": "html"
  }

Conslusion

That’s pretty much it. I would highly advise you to remove any other Ruby extensions that you might have installed. Installing several formatters usually leads to conflicts and ironically, not a single one works.