How to automatically format Ruby or .erb files in VS Code?

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

Instead of formatting the document, he prints this letter: Ï

How do I get it to format a document?

+15
source share
6 answers

You can set format associations in VSCode, so .erb files will be processed as .html.

Go to File-> Settings β†’ Settings-> Click ... in the upper right corner corner-> Open the settings.json file.

Then add this piece of code to your settings.json file

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

This is how I solved this problem. It will remove some of the highlighted sections of the code, but will automatically format the HTML templates, such as an HTML document.

+15
source

Currently (March 2019), I think a prettier-ruby option is a better option: it can work with Ruby, ERB (like HTML), JS and many others.

 prettier script.rb # will show you the formatted script prettier --write script.rb # will overwrite the file with the formatted script 

You can use the Prettier VS Code plugin to do this automatically: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

https://github.com/prettier/plugin-ruby

+2
source

VSCode does not have native support for formatting Ruby files, but you can easily install the extension that adds this. Here's how to get started with the Ruby extension :

The format document command should now work for Ruby files.

Hope that helps

+1
source

You can use Rufo to format your Ruby code. This is a formatted opinion (e.g. Prettier for JS if you are familiar with it).

You can use the vscode-rufo extension to integrate it with VSCode.

+1
source
 gem install htmlbeautifier 

using the search function provided in the editor with Ctrl + Shift + P (or Command + Shift + P on Mac), and then look for the document format .

0
source

To format your ruby ​​files, you do not need an additional plugin, you can just map some keys to do "editor.action.reindentLines"

If you are using the vscode-vim plugin, you can add this to your settings:

  "vim.normalModeKeyBindingsNonRecursive": [ { "before": ["=", "="], "commands": ["editor.action.reindentlines"] } ], 

Then, in normal mode, vim == reformat your file.

0
source

Source: https://habr.com/ru/post/1261023/


All Articles