Last active
February 5, 2020 00:42
-
-
Save smtlaissezfaire/63ab4246c05c0b17dc9b19d8a310d685 to your computer and use it in GitHub Desktop.
Lookup migration by file name, then get the version number (rails). Handy for migrating up + down based on the migration name (for instance `rake db:migrate VERSION=$(migration_before create_users)`)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
name = ARGV[0] | |
verbose = ARGV[1] == "--verbose" | |
if name.nil? || name.empty? | |
puts "" | |
puts "\tUsage: migration_before <migration_name> [--verbose]" | |
puts "" | |
puts "\tLookup migration by file name, then get the version number (rails). " | |
puts "\tHandy for migrating up + down based on the migration name (for instance " | |
puts "\t`rake db:migrate VERSION=$(migration_before create_users)`)" | |
puts "" | |
puts "\tExample Output:" | |
puts "\t\t$ migration_before create_users" | |
puts "\t\t20200113191953" | |
exit -1 | |
end | |
files = Dir.glob("db/migrate/*.rb").sort.reverse | |
matching_index = nil | |
reversed_files = files.reverse | |
reversed_files.each_with_index do |file, index| | |
file =~ /(\d+)_(.*)\.rb/ | |
migration_name = $2 | |
if verbose | |
puts "file: #{file}" | |
end | |
if migration_name.include?(name) | |
if verbose | |
puts "matching migration: #{migration_name} (#{file})" | |
end | |
matching_index = index | |
end | |
end | |
if !matching_index | |
raise "* no matching index with name: #{name}" | |
end | |
file_before = reversed_files[matching_index - 1] | |
version_before = (file_before =~ /(\d+)_(.*)\.rb/) && $1 | |
if verbose | |
puts "* Found Matching File: #{reversed_files[matching_index]}" | |
puts "* Migrating to: #{file_before} (#{version_before})" | |
end | |
puts version_before |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment