I’ve recently added RuboCop to one of my existing, large Ruby projects. A lot of the style adjustments RuboCop was able to apply automatically, but a significant number of files was still left for me to fix.

Opening each file manually seemed like a hassle so I’ve prepared this script that opens $EDITOR on each offense, waits for user to modify the file and goes to the next offense. It’s tuned for MacVim/Vim, but any editor that doesn’t detach from shell should work. This saved me tremendous amounts of time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require "rubocop"

class OpenEditor < RuboCop::Formatter::ProgressFormatter
  VimFamily = %w{vim gvim mvim}

  def report_file file, offenses
    super

    if editor_supports_lines?
      offenses.each do |offense|
        run_editor file, offense unless offense.corrected?
      end
    else
      run_editor file
    end
  end

  def editor
    ENV["EDITOR"]
  end

  def editor_supports_lines?
    VimFamily.include? editor
  end

  def run_editor file, offense = nil
    if offense
      args = args_with_offense file, offense
    else
      args = args_without_offense file
    end

    original_modification_time = File.mtime file

    system editor, *args

    return if original_modification_time != File.mtime(file)

    output.puts "No changes made to the file. Aborting."
    exit 1
  end

  def args_with_offense file, offense
    case editor
    when *VimFamily
      # Text vim will hide our console output, so we need to echo the message again
      # inside vim.
      message = offense.message.to_s
        .gsub('"', "double quote")
        .gsub("'", "quote")

      [
        "+#{offense.line}",           # go to line
        "-f",                         # gvim/mvim will not detach from shell
        "-c", "echomsg '#{message}'",
        file
      ]
    else
      [file]
    end
  end

  def args_without_offense file
    [file]
  end
end

And use it like this:

1
rubocop -r ./editor.rb -f OpenEditor