Ruby - Use Rubocop on VS Code

·

2 min read

Don't want to run Rubocop command on the terminal? Try it on VS Code!

Prepare to install

If you are using macOS, please follow this blog post to install Ruby in a macOS for local development. When you installed rbenv completely, check the .ruby-version file in your project and install that version.

# install a Ruby version:
rbenv install 3.1.2

# set the default Ruby version for this machine
rbenv global 3.1.2
# or:
# set the Ruby version for this directory
rbenv local 3.1.2

which ruby
# output: /Users/{user-name}/.rbenv/shims/ruby

Make sure that you can run the ruby command on your shell:

ruby -v
# output is ruby version

gem install rubocop
which rubocop

If you are using "zsh" shell and ruby from brew, make sure that you added the lines below to ~/.zshrc:

# ruby
if [ -d "/opt/homebrew/opt/ruby/bin" ]; then
  export PATH=/opt/homebrew/opt/ruby/bin:$PATH
  export PATH=`gem environment gemdir`/bin:$PATH
fi

Now, let's install the Ruby Rubocop extension on VS Code.

Configuration

Open your VS Code configuration by pressing command + shift + p and input the JSON text.

Then choose the Open User Settings (JSON) feature.

Specify the configuration below if you want.

{
  // If not specified searches for 'rubocop' executable
  // available on PATH (default and recommended)
  "ruby.rubocop.executePath": "",

  // You can use specific path
  // "ruby.rubocop.executePath": "/Users/you/.rbenv/shims/"
  // "ruby.rubocop.executePath": "/Users/you/.rvm/gems/ruby-2.3.2/bin/"
  // "ruby.rubocop.executePath": "D:/bin/Ruby22-x64/bin/"

  // If not specified, it assumes a null value by default.
  "ruby.rubocop.configFilePath": "/path/to/config/.rubocop.yml",

  // default true
  "ruby.rubocop.onSave": true
}

How to use it?

To use this extension, press command + shift + p and input the rubocop text.

We hare 2 options:

  • "Lint by rubocop": lint the current ruby file and show warning if Rubocop found problems.

  • "autocorrect by rubocop": lint the current ruby file and auto fix that problems if Rubocop can.

Happy coding!