Enable Formatting with ERB files in VScode

I was searching online for a ERB beautifier and couldn’t find a complete solution that I could use on my Ubuntu and MacOS setup.

In order to solve this problem I created a task where it runs HTMLbeautifier that is capable of understanding embedded Ruby.


Step 0 Install HTML Beautifier :

Install the gem by writing gem install htmlbeautifieron your terminal.

Step 1 Create a task file:

Click on the Tasks on the top of your VScode, then select the Configure Tasks, then select the Create tasks.json from template and after that click Other.

Now a json file will be created with the following formatting :

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
    "label": "echo",
    "type": "shell",
    "command": "echo Hello"
}
         ]
}

Step 2 Modify the Task file:

{
"version": "2.0.0",
"tasks": [
{
    "label": "ERB formatter",
    "type": "shell",
    "command": "ext=$(echo ${file})  && if [ ${ext##*.} == erb ]; then htmlbeautifier ${file} ${file}; else echo 'Not an ERB file'; fi",
    "presentation": {
        "reveal": "never",
        "panel": "new",
        "echo": false
       },
    "group": {
    "kind": "build",
    "isDefault": true
     }
}
            ]
}

Now let’s break the commands in pieces. The "version":"2.0.0" is used to defined which version of task are we going to use with our VScode. Then the label is the name of our task.

Now the command

ext=$(echo ${file})
if [ ${ext##*.} == erb ]; then
htmlbeautifier ${file} ${file};
else
echo 'Not an ERB file';
fi
// The ${file} is a predefined variable that gives you the active file in your VScode tab.
// The following command ${ext##*.} is taking the biggest substring of a string (signle # would take the smallest part) until it meets the last period character. For example the name test.erb , would give you the output erb and the name test.txt would give you txt
// Now if the erb condition is met, then we should run htmlbeautifier with input and output the absolute path of the file

Step 3 Create a shortcut:

Wrapping up, we need a shortcut in order to run our task with ease. To do this open keybindings.json and paste the following

{
"key": "cmd+shift+r",
"command": "workbench.action.tasks.runTask",
"args": "ERB formatter"
}

This will run ERB formatter everytime your press cmd (if on MacOS) ,shift and r.


That was pretty much all of it. Hope you find it useful 🙌