jesseduffield/lazy_migrate

[Tutorial] Using lazy_migrate with rails 7.1

Opened this issue · 0 comments

It's been a long time since any update from this gem
And some internal/API/whatever changes in active record is making this gem unusable
I am here to share some monkey patches so you can use this gem with new rails versions

Rails 7.1

I use sane_patch to ensure I got error when this gem is updated
You can remove it entirely

# config/initializers/lazy_migrate_monkey_patches.rb

require "lazy_migrate"

SanePatch.patch("lazy_migrate", "0.3.0") do
  # Compatibility for rails 7
  module LazyMigrate
    # rubocop:disable Style/StaticClass
    class Client
      class << self
        def run
          migrator_adapter = MigratorAdapterFactory.create_migrator_adapter

          loop do
            catch(:done) do
              on_done = -> { throw(:done) }

              database_name = if ActiveRecord::Base.respond_to?(:connection_db_config)
                # Rails 7
                ActiveRecord::Base.connection_db_config.database
              else
                # Rails 6-
                ActiveRecord::Base.connection_config[:database]
              end
              prompt.ok("\nDatabase: #{database_name}\n")

              select_migration_prompt(on_done: on_done, migrator_adapter: migrator_adapter)
            end
          end
        rescue TTY::Reader::InputInterrupt
          puts
        end
      end
    end

    class MigratorAdapter
      # From 0.3.0
      def dump_schema
        return if !ActiveRecord.dump_schema_after_migration

        # ripped from https://github.com/rails/rails/blob/5-1-stable/activerecord/lib/active_record/railties/databases.rake
        filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema.rb")
        File.open(filename, "w:utf-8") do |file|
          ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
        end
      end
    end
    # rubocop:enable Style/StaticClass
  end
end