rubyvisual-studio-coderubocop

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


Environments

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?


Solution

  • 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.