Skip to content

Instantly share code, notes, and snippets.

@smcabrera
Last active May 14, 2025 17:11
Show Gist options
  • Save smcabrera/bf474858ab064764cf22d1728d439ca0 to your computer and use it in GitHub Desktop.
Save smcabrera/bf474858ab064764cf22d1728d439ca0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'fileutils'
require 'active_support/core_ext/string' # For underscore method
# Function to extract the migration class name from the file path
def extract_migration_class_name(file_path)
migration_file_name = File.basename(file_path, '.rb')
# Convert the rest of the filename (after timestamp) to CamelCase
migration_file_name.split('_')[1..].map(&:capitalize).join
end
# Function to move the migration file using `git mv`
def move_migration_with_git(old_file_path, new_file_path)
system("git mv #{old_file_path} #{new_file_path}")
puts "Renamed migration file from #{old_file_path} to #{new_file_path} using git mv."
end
# Main function to run the script
def process_migration(file_path)
# Read the contents of the target file into a variable
migration_contents = File.read(file_path)
migration_class_name = extract_migration_class_name(file_path)
system("rm #{file_path}")
# Run the Rails migration generator
system("rails generate migration #{migration_class_name}")
# Get the name of the newly generated migration file
migrations_path = File.join(Dir.pwd, 'db/migrate')
new_migration_file = Dir.glob("#{migrations_path}/*.rb").max_by { |f| File.mtime(f) }
File.open(new_migration_file, 'wb') { _1.puts migration_contents }
# Output the name of the new migration file
puts "New migration file created: #{new_migration_file}"
puts 'Migration update completed successfully.'
end
# Get the file path argument and run the process
if ARGV.length != 1
puts 'Usage: ruby regenerate_migration.rb path_to_migration_file'
exit 1
end
file_path = ARGV[0]
process_migration(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment