Class: Newshound::Middleware::BannerInjector

Inherits:
Object
  • Object
show all
Defined in:
lib/newshound/middleware/banner_injector.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ BannerInjector

Returns a new instance of BannerInjector.



6
7
8
# File 'lib/newshound/middleware/banner_injector.rb', line 6

def initialize(app)
  @app = app
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
# File 'lib/newshound/middleware/banner_injector.rb', line 10

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

  # Only inject into HTML responses
  return [status, headers, response] unless html_response?(headers)
  return [status, headers, response] unless status == 200

  # Check authorization
  controller = env["action_controller.instance"]
  return [status, headers, response] unless controller
  return [status, headers, response] unless Newshound::Authorization.authorized?(controller)

  # Get banner HTML
  banner_html = generate_banner_html

  # Inject banner after <body> tag
  new_response = inject_banner(response, banner_html)

  # Update Content-Length header
  if headers["Content-Length"]
    headers["Content-Length"] = new_response.bytesize.to_s
  end

  [status, headers, [new_response]]
end