Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I auto format Ruby or .erb files in VS Code?

I press + + F in Visual Studio Code for macOS, the shortcut to Format Document, to format a file called foo.rb or foo.html.erb.

Instead of formatting the document it prints out this letter: Ï

How do I get it to format the document?

like image 922
Derek Avatar asked Dec 09 '16 00:12

Derek


People also ask

How do I automatically format code in Visual Studio code?

The code formatting is available in Visual Studio Code through the following shortcuts: On Windows Shift + Alt + F. On Mac Shift + Option + F. On Linux Ctrl + Shift + I.

Can prettier format Ruby?

To run prettier with the Ruby plugin, you're going to need ruby (version 2.7. 3 or newer) and node (version 8.3 or newer). If you're integrating with a project that is not already using prettier , you should use the Ruby gem. Otherwise you can use the npm package directly.


2 Answers

You can set format associations in VSCode, so .erb files would be treated like .html.

Go to File->Preferences->Settings->Click ... in top right corner->Open settings.json

Then add this piece of code to your settings.json

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

This is how I solved this problem. It will remove some of the code highlights but will autoformat HTML templates like an HTML document.

like image 77
Никита Львов Avatar answered Oct 17 '22 07:10

Никита Львов


You're going to need all of these settings in VS Code's settings.json file:

"ruby.rubocop.onSave": true, "editor.formatOnSaveTimeout": 5000, "editor.formatOnSave": true, "files.associations": {     "*.erb": "erb" }, 

Save the settings file. Install the "ruby-rubocop" and "ERB Formatter/Beautify" extensions on VS Code. Follow the documentation on both of those extensions to install their gem dependencies. Restart VS Code.

Format-on-save functionality will only trigger if the file is actually saved (which only happens if you change the file). Saving a file that has no changes will not trigger format-on-save.

like image 30
Andrew Koster Avatar answered Oct 17 '22 08:10

Andrew Koster