Class: Arlequin::Middleware

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

Overview

Middleware to detect and warn about N+1 queries in a Rails application.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Initializes the middleware with the given app.

Parameters:

  • app (Object)

    The Rack application this middleware wraps.



11
12
13
# File 'lib/arlequin/middleware.rb', line 11

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Array

Processes the incoming request, detects N+1 queries, and injects a warning into the HTML response if necessary.

Parameters:

  • env (Hash)

    The Rack environment.

Returns:

  • (Array)

    The status, headers, and response of the Rack application.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/arlequin/middleware.rb', line 21

def call(env)
  @queries = Hash.new { |hash, key| hash[key] = 0 }
  ActiveSupport::Notifications.subscribe("sql.active_record", &method(:on_sql))

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

  if n_plus_one_detected?
    html_fragment = generate_html_warning
    response = inject_html_fragment(response, html_fragment)
  end

  ActiveSupport::Notifications.unsubscribe("sql.active_record")

  [ status, headers, response ]
end