Rails: Auto-Formatting on VSCode

Flavio Wuensche
2 min readJul 5, 2023

Use Syntax Tree to auto-format Ruby on Rails files on Visual Studio Code.

Photo by Pawel Czerwinski on Unsplash

Auto code formatters like prettier bring several benefits to the table.

  • They save you valuable time by automatically formatting your code, eliminating the need for manual formatting.
  • They ensure code is consistent and readable code across your entire project.
  • They reduce code review discussions related to formatting, making collaboration smoother.

Overall, you can focus on writing code without worrying about formatting rules. So, let's setup your Rails project so it can handle the formatting, while you enjoy the pure pleasure of coding.

Install the syntax_tree gem

You're only going to need one new dependency:

gem 'syntax_tree'

Then from the command line:

bundle install

Setup a .streetrc file

We can now setup a .streerc file at the root of the project:

--print-width=120
--plugins=plugin/single_quotes,plugin/trailing_comma
--ignore-files='**/node_modules/**'
--ignore-files='vendor/**'

Prevent conflicts with Rubocop

RuboCop and Syntax Tree serve different purpose, but there's is some overlap with RuboCop, so Syntax Tree provides a Rubocop configuration file to disable rules that are redundant with Syntax Tree.

To use this configuration file, add the following snippet to the top of your project’s .rubocop.yml:

inherit_gem:
syntax_tree: config/rubocop.yml

Install the VS Code extension

Probably the easiest step. You’ll also need one extension from the VS Code marketplace: https://marketplace.visualstudio.com/items?itemName=ruby-syntax-tree.vscode-syntax-tree

Modify your VS Code settings

Lastly, you'll need to make sure VS Code is using the right code formatter to auto-format your Ruby files. You can set up a different value for Ruby files if you also use another code formatter such as Prettier.

This is what I do, so my settings.json file looks like the following:

"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[ruby]": {
"editor.defaultFormatter": "ruby-syntax-tree.vscode-syntax-tree"
},

Was this article helpful to you? 🙃

I regularly share practical tips to improve your productivity as a developer. Mainly focused on Rails, React, and VS Code. Subscribe for more →

--

--

Flavio Wuensche

Building an open-source tool to keep track of technical debt on large codebases 🍒 cherrypush.com