Sha256: 591ef922eccd13960592ec386656fda38c301ccbfc8fee8920a8bc4cd2336af0

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

module ActiveRecordMigrationUi
  #
  # Intercepts the ActiveRecord::PendingMigrationError and loads the engine's
  # MigrationsController.
  #
  # Demystified thanks to https://aashishgarg.github.io/rails/sample-rack-application/
  #
  class Middleware
    def initialize(app)
      # The next middleware to be called.
      @app = app
    end

    def call(env)
      if database_needs_migration? && not_ar_migration_ui_request?(env)
        # Pending migration detected, move to the entrypoint controller
        MigrationsController.call(env)
      else
        @app.call(env) # Move to the next middleware (See `rake middleware`)
      end
    end

    private

    def database_needs_migration?
      ActiveRecordMigrationUi.needs_migration?
    end

    def not_ar_migration_ui_request?(env)
      return false unless env['REQUEST_PATH']

      not_a_webpack_request?(env) && not_a_cable_request?(env)
    end

    def not_a_webpack_request?(env)
      webpack_request?(env) == false
    end

    def webpack_request?(env)
      env['REQUEST_PATH'].starts_with?('/ar-migration-ui-packs/')
    end

    def not_a_cable_request?(env)
      cable_request?(env) == false
    end

    def rails_action_cable_mount_path
      Rails.configuration.action_cable.mount_path
    end

    def cable_request?(env)
      return false unless rails_action_cable_mount_path

      env['REQUEST_PATH'].starts_with?(rails_action_cable_mount_path)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record_migration_ui-0.1.2 lib/active_record_migration_ui/middleware.rb