Skip to content

Instantly share code, notes, and snippets.

@amkisko
Last active May 3, 2024 07:24
Show Gist options
  • Save amkisko/b4b24a960a5b9d52b591f3b49b081d8b to your computer and use it in GitHub Desktop.
Save amkisko/b4b24a960a5b9d52b591f3b49b081d8b to your computer and use it in GitHub Desktop.
Rails database migrations cleaner/archiver/squasher
namespace :db do
namespace :migrate do
task archive: :environment do
Rake::Task["db:migrate"].invoke
expires_in = 90.days
files = Dir.glob(Rails.root.join("db/migrate/*").to_s)
files.each do |path|
name = File.basename(path)
timestamp, _ = name.split("_", 2)
date = Time.zone.parse(timestamp)
next if date.since(expires_in).future?
puts "Archiving #{name}"
if ENV["DRY_RUN"].blank?
archive = File.open(Rails.root.join("db/migrate_archive.rb"), "a")
archive.puts("# #{name}")
archive.puts(File.read(path))
archive.puts
FileUtils.rm(path)
end
end
Rake::Task["db:migrate"].invoke
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment