Class: RailsWayback::BarMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_wayback/bar_middleware.rb

Overview

Rack middleware that appends the wayback bar to every successful HTML response of the host application while the gem is enabled. Skips assets, ActionCable, non-2xx responses and non-HTML bodies so it never touches anything but the developer-facing pages.

Constant Summary collapse

SKIP_PATH_PREFIXES =
%w[
  /assets
  /packs
  /rails/
  /cable
  /rails-wayback
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ BarMiddleware

Returns a new instance of BarMiddleware.



20
21
22
# File 'lib/rails_wayback/bar_middleware.rb', line 20

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rails_wayback/bar_middleware.rb', line 24

def call(env)
  # Always reset the per-request render tracker before invoking the
  # app so the middleware can accurately report which templates the
  # current page rendered. Cheap and thread-safe (Thread.current).
  Thread.current[RailsWayback::RENDER_TRACKER_KEY] = []

  status, headers, body = @app.call(env)
  return [status, headers, body] unless inject?(env, status, headers)

  html = read_body(body)
  snippet = build_snippet(env)
  new_html = inject(html, snippet)

  new_headers = headers.dup
  length_key = new_headers.key?("Content-Length") ? "Content-Length" : (new_headers.key?("content-length") ? "content-length" : nil)
  new_headers[length_key] = new_html.bytesize.to_s if length_key

  [status, new_headers, [new_html]]
end