require 'rails/generators/active_record' module ForeignKeyChecker module Generators class MigrationGenerator < ActiveRecord::Generators::Base desc "generates the necessary migrations to fix foreign_key problems" argument :name, type: :string, default: 'FixForeignKeys' source_root File.expand_path('templates', __dir__) def create_migrations @class_name = name.camelcase.tr(':', '') file_name = name.underscore.tr('/', '_') @done = Dir.glob(Rails.root.join('db', 'migrate', '*.rb')).map do |path| File.open(path).readlines.find { |line| line.include?('ActiveRecord::Migration') && line.include?(@class_name) } end.compact.size @checks = ForeignKeyChecker.check(zombies: false, indexes: false) unless @behavior == :revoke if @behavior == :revoke @file_suffix = "_v#{@done}" if @done > 1 @class_suffix = "V#{@done}" if @done > 1 else @file_suffix = "_v#{@done + 1}" if @done > 0 @class_suffix = "V#{@done + 1}" if @done > 0 end migration_template 'migrations/fix_foreign_keys.rb.erb', "db/migrate/#{file_name}#{@file_suffix}.rb" end end end end