Ruby on Rails

Ignoring existing database migrations with Rubocop

Adding Rubocop to an existing code base can be daunting. You’ll probably get 100s, if not 1000s of offences that you need to look at.

One thing that stuck out and that I didn’t really care about were all the existing database migrations.

The easy solution would be to just ignore the whole directory, but I wanted it to lint new migrations. I just don’t care about fixing style issues in the already existing ones, since that code will probably be never ran or even looked at again (a lot has been written if you even need to keep them around, but that’s a different discussion).

The best solution (inspired by what Gitlab did) is to just ignore all existing files via a magic comment. I wrote a little script to automatically add that:

Dir.glob("db/migrate/*.rb") do |file|
  current =
  new = "# rubocop:disable all\n\n#{current}"

  File.write(file, new)

Just run it once from the root directory of your app and you’ll probably get rid of a ton of offences immediately. Future migrations will be linted and style checked.