Class: Mbeditor::Rack::HandlePendingMigrations

Inherits:
Object
  • Object
show all
Defined in:
lib/mbeditor/rack/handle_pending_migrations.rb

Overview

Catches ActiveRecord::PendingMigrationError for mbeditor routes so the editor remains usable (e.g. to edit migration files) even when migrations are pending. Non-mbeditor routes are unaffected and still raise normally.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ HandlePendingMigrations

Returns a new instance of HandlePendingMigrations.



9
10
11
# File 'lib/mbeditor/rack/handle_pending_migrations.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/mbeditor/rack/handle_pending_migrations.rb', line 13

def call(env)
  @app.call(env)
rescue => e
  raise unless defined?(ActiveRecord::PendingMigrationError) && e.is_a?(ActiveRecord::PendingMigrationError)

  path = "#{env["SCRIPT_NAME"]}#{env["PATH_INFO"]}"
  raise unless path.start_with?("/mbeditor")

  if env["HTTP_X_MBEDITOR_CLIENT"] == "1"
    # XHR from the editor frontend — structured JSON error.
    # The frontend axios interceptor shows a banner on this response.
    body = JSON.generate(pending_migration_error: e.message.strip)
    [503, { "Content-Type" => "application/json" }, [body]]
  else
    # HTML page load. Serve the editor shell so devs can edit migration
    # files. Assets are referenced by their unfingerprinted paths, which
    # Sprockets resolves in development (the only env mbeditor runs in).
    # The banner appears as soon as the first XHR fires.
    base = env["SCRIPT_NAME"].to_s.sub(%r{/$}, "")
    [200, { "Content-Type" => "text/html; charset=utf-8" }, [editor_shell_html(base)]]
  end
end