I'm trying to integrate Rubocop's formatter in an editor: given some Ruby code as an input, return a string representing the equivalent formatted code. I was considering the -s option as suggested by Rubocop's help:
-s FILE - Pipe source from STDIN, using FILE in offense reports. This is useful for editor integration.
In a terminal, the following command successfully reads the input contents and prints the formatted output to stdout:
cat some_file.rb | rubocop -a -f fi -s some_file.rb
However, I'm not able to programmatically reproduce something similar using the Rubocop API. I was hoping to somehow feed the input to a RuboCop::Runner, however, simply parsing the options hangs before I get to that point:
require 'rubocop'
input = "some_var = 'hello'"
options, paths = RuboCop::Options.new.parse(['-a', '-f', 'fi', '-s', 'some_file.rb'])
runner = RuboCop::Runner.new(options, RuboCop::ConfigStore.new)
...
Of course, one option would be to drop -s and operate on temporary files, but that adds complexity and is less efficient.
How do I conveniently produce a formatted output using the API?
Just call RuboCop as an external process, e.g. using Open3.capture2:
stdout_str, status = Open3.capture2("rubocop -a -f fi -s some_file.rb", input)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With