Class: RailsI18nOnair::LiveUi::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_i18n_onair/live_ui/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



4
5
6
7
8
# File 'lib/rails_i18n_onair/live_ui/middleware.rb', line 4

def initialize(app)
  @app = app
  @mount_path    = nil
  @cached_script = nil
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rails_i18n_onair/live_ui/middleware.rb', line 10

def call(env)
  # Fast exit: skip all work when Live UI is off
  return @app.call(env) unless RailsI18nOnair.configuration.live_ui?

  translator = translator_signed_in?(env)

  # Determine if this request should get Live UI treatment.
  # Set the flag via CurrentAttributes BEFORE the app renders —
  # the t() helper reads Current.live_ui_active during view rendering.
  active = env["REQUEST_METHOD"] == "GET" &&
           !engine_request?(env) &&
           translator

  RailsI18nOnair::Current.live_ui_active = active

  status, headers, response = @app.call(env)

  if translator && status == 200 && html_response?(headers) && rewritable_response?(headers)
    body = collect_body(response)
    response.close if response.respond_to?(:close)
    # Replace ⟦i18n:key:locale⟧text⟦/i18n⟧ markers from controller t()
    # calls (flash messages, etc.) with editable <span> wrappers.
    body = replace_i18n_markers(body)
    # Remove wrappers that ended up where markup cannot live —
    # attribute values (placeholder:, title:, …), <title>, <textarea>.
    body = unwrap_misplaced_spans(body)
    body = inject_live_ui(body) if active
    headers["Content-Length"] = body.bytesize.to_s
    [status, headers, [body]]
  else
    [status, headers, response]
  end
end