Last Updated: February 25, 2016
·
750
· EnriqueVidal

Update version on rails migrations

If you ever need to change the version on a migration file, there's an easy way to do it:

mv {20121124202614,$(date +%Y%m%d%H%M%S)}_my_migration.rb

With 20121124202614 being the current migration version.

But that looks pretty long to write and not very useful the way it's written right now.

We can write a small ruby script to handle this for us, something like this will do.

#!/usr/bin/env ruby

require 'fileutils'

ARGV.each_with_index do |file, index|
  next unless File.exists?( file )

  filename_arr = File.basename( file ).split '_'

  # Make sure to add a couple of seconds
  new_version = Time.now.strftime( '%Y%m%d%H%M%S' ).to_i + index

  # Change the version
  filename_arr[0] = new_version
  new_name = filename_arr.join '_'

  new_file = File.join File.dirname( file ), new_name

  # Rename in filesystem
  FileUtils.mv file, new_file
end

Put it somewhere in your $PATH like ~/bin name it version_change or whatever you like and make it executable:

chmod 755 ~/bin/version_change

We now have a couple of advantages we didn't have before:

  • We can update multiple files like this:

ls db/migrate/* | xargs version_change

  • The list can be in any order we need it to be and the script will respect that order:

version_change 002_latest.rb 001_first.rb

  • Ruby is a really neat language so updating the script is now a breeze.
  • You can update the filenames of any files that follow the same format the rails migrations do.