We recently needed to create a new database migration, and needed to insert it into at certain position. Normally what I have done in the past is to alter the migration index of an existing file or two.
But this time, it needed to go in at 003. I was going to have to manually increment about 30 or 40 migration scripts. So, it was time to apply my Ruby skills to do it automatically.
Here is the result:
case ARGV.size
when 1, 2
from_index = ARGV[0].to_i
dir = Dir.new(‘.’)
file_list = dir.to_a.sort
file_list.each do |fn|
if fn =~ /(\d{3})(.*\.rb)/
index = $1.to_i
if index >= from_index
index += 1
new_name = case index.to_s.length
when 1
“00#{index}#{$2}”
when 2
“0#{index}#{$2}”
else
“#{index}#{$2}”
end
puts “Converting ‘#{fn}’ to ‘#{new_name}’”
File.rename fn, new_name if ARGV[1] == “RUN”
else
puts “Skipping ‘#{fn}’”
end
else
puts “Ignoring ‘#{fn}’”
end
end
else
puts “Usage: #{$0}
puts ” where”
puts ” number – migration number to start from (mandatory)”
puts ” RUN – add to run to make the changes (default does not rename)”
end
So when you run it, you will get output such as:
Instructions
- Cut and paste the file, or download it from increment_migrations.rb.
- Save it somewhere
- Make it executable
chmod 755 /path/to/increment_migrations.rb - The change directory to ./db/migrations
- then run
/path/to/increment_migrations.rb 3 - and if the output looks as expected
- finally run
/path/to/increment_migrations.rb 3 RUN
Finally, thanks to the client for permission to publish. Thanks for giving back to the community!