/ Programming

Upgrading to Rails 5 using vim shortcuts

Following the rails upgrade guide there's a number of find and replace tasks which can be automated with a little vim scripting.

For example, ActiveRecord models no longer inherit from ActiveRecord::Base. Instead they inherit from ApplicationRecord. Updating is a simple find and replace operation for those other IDEs right?

It's simple in Vim too.

First, tell vim where to search by adding the potential files to the :arg list. You don't have to do this step and have vim search every file in your project, but that's slow when you know where vim should be looking anyways.

:argadd app/models/**/*.rb

You can view and confirm what was added with the command :arg.

Then, run a %s substitution operation on the entire file list with :argdo:

:argdo %s/ActiveRecord::Base/ApplicationRecord/gce | update

The gce tells vim to:

g: globally replace in the files
c: confirm before changing
e: ignore the 'no match found in file' errors

Piping this command to update automatically saves the modified buffers.

Not as simple as an IDE, but no mouse clicks is always a win!


For the rspec fans out there, the below substitution command will help you update controller tests. Be warned this doesn't handle multi-line replacements, but should get you most of the way:

%s/(get|put|post|delete) :(\w*), (params)@!(.*)$/\1 :\2, params: { \3\4 }/gce

Upgrading to Rails 5 using vim shortcuts
Share this