vscode( vscode-ruby + rubocop ) how to auto correct on save?

kukrt picture kukrt · Dec 30, 2017 · Viewed 20.6k times · Source

Environments

  • vscode Version 1.19.1 (1.19.1)
  • rubocop (0.52.1)
  • Darwin mbp 16.7.0 Darwin Kernel Version 16.7.0: Wed Oct 4 00:17:00 PDT 2017; root:xnu-3789.71.6~1/RELEASE_X86_64 x86_64
  • ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-darwin16]

followed https://github.com/rubyide/vscode-ruby#linters and installed all gems and edited the settings.json like this.

{

  "ruby.rubocop.executePath": "/Users/ac/.rbenv/shims/",
  "ruby.rubocop.onSave": true,
  "ruby.lint": {
    "ruby": {
      "unicode": true //Runs ruby -wc -Ku
    },
    "reek": true,
    "rubocop": {
      "lint": true,
      "rails": true
    },
    "fasterer": true,
    "debride": {
      "rails": true //Add some rails call conversions.
    },
    "ruby-lint": true
  },
  "ruby.locate": {
    "include": "**/*.rb",
    "exclude": "{**/@(test|spec|tmp|.*),**/@(test|spec|tmp|.*)/**,**/*_spec.rb}"
  }

}

On vscode, code highlighting is working fine.
*just to note, you see the extensions installed, and warnings in the problem tab.

rubocop is working ok

Question

I was under the inpression that vscode-ruby and rubocop would auto-correct indentations and cop rules on file save, but apparently it doesn't.
If I want it to format my code like prettier, how should I set this up?

Answer

MattD picture MattD · Dec 14, 2018

Per this comment on the vscode-ruby-rubocop GitHub, you can use the following settings:

{
    "editor.formatOnSave": true,
    "editor.formatOnSaveTimeout": 5000,
    "ruby.rubocop.executePath": "path/where/rubocop/is/located",
    "ruby.format": "rubocop",
}

Just applied them to my user settings on my local box and it appears to work. VS Code was throwing an error for my ruby.rubocop.executePath setting saying it wasn't executable, and removing the line appears to not cause that error to show, and still formats my code accordingly. Setting a lower timeout (I tried 2500) also seems to break auto format on saving, so I'd suggest leaving it at 5000.