If you want to have your code formatted by rubocop without waiting for seconds, you are reading the right article.
At Doctolib, we have a lot of rubocop rules to keep our Ruby code readable by everyone.
But not everyone is familiar with all these rules, and fixing them by launching the rubocop script in the terminal can be a nightmare.
That’s why having the rubocop extension in VScode changes your life, you have immediate feedback of your errors, and it can automatically format the code for some rules.
I’ve peer coded with my colleague Lionel and I saw that he deactivated the auto format function for Ruby because it takes up to 4 seconds to save a simple file.
Rather than removing this super cool feature of VScode, I tried to find a way to make it faster.
And I found this gem which is underestimated in the Ruby community, and makes rubocop much faster rubocop-daemon
I made some speed tests on big files and the difference is breathtaking:
- On the first save, it takes on average 2.7s with the normal rubocop for a file of 1K+ lines of code, and only 0.57s with the rubocop-daemon. It’s 5x faster!
- Both tools are caching the file, so if you relaunch it for the same file, it will take 1.49s with the normal rubocop, and 0.07s with rubocop-daemon. It’s 20x faster!
gem 'rubocop-daemon', require: false
Or if you don’t want to add it only on your computer, just launch:
gem install rubocop-daemon
Each time you need it, start the server, run:
The rubocop server will run in the background until you switch off your computer.
Now, we want to replace the old command rubocop with the rubocop-daemon-wrapper, so you will be able to launch rubocop the same way as before.
curl https://raw.githubusercontent.com/fohte/rubocop-daemon/master/bin/rubocop-daemon-wrapper -o /tmp/rubocop-daemon-wrapper sudo mkdir -p /usr/local/bin/rubocop-daemon-wrapper sudo mv /tmp/rubocop-daemon-wrapper /usr/local/bin/rubocop-daemon-wrapper/rubocop sudo chmod +x /usr/local/bin/rubocop-daemon-wrapper/rubocop
We now need to add the command to our terminal.
Add this line at the end of your .zshrc or .bashrc file and save it.
Relaunch your terminal.
Last step: Override rubocop with a symlink to rubocop-daemon-wrapper
If you use rvm, run this command:
ln -fs /usr/local/bin/rubocop-daemon-wrapper $(which rubocop)
Or if you use rbenv:
ln -fs /usr/local/bin/rubocop-daemon-wrapper $(rbenv which rubocop)
And that’s it!
You can now run rubocop as before, and VScode will use the fast rubocop.
Don’t forget to add the rubocop VScode extension if you don't have it.
And activate the “format on save” and “format on paste”:
Open preferences with
Format on save /
Format on paste and activate them.
Ta-da, your code will be automagically formatted by rubocop at the lightning speed 🚀