Class: ActiveRecordQueryCount::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



6
7
8
# File 'lib/active_record_query_count/middleware.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
# File 'lib/active_record_query_count/middleware.rb', line 10

def call(env)
  return @app.call(env) unless Configuration.enable_middleware

  status, headers, response, query_count_data = nil
  ActiveRecordQueryCount.start_recording
  status, headers, response = @app.call(env)
  query_count_data = ActiveRecordQueryCount.tracker.active_record_query_tracker.clone
  ActiveRecordQueryCount.end_recording(printer: :none)
  if headers['Content-Type']&.include?('text/html') && response.respond_to?(:body) && response.body['<body']
    response_body = inject_query_counter_js(response.body, query_count_data)
    headers['Content-Length'] = response_body.bytesize.to_s
    response = [response_body]
  end
  [status, headers, response]
end

#inject_query_counter_js(response_body, query_count_data) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/active_record_query_count/middleware.rb', line 26

def inject_query_counter_js(response_body, query_count_data)
  injected_html = ::ActiveRecordQueryCount::Printer::Html.new(data: query_count_data).inject_in_html
  # Parse the response body with Nokogiri
  doc = Nokogiri::HTML(response_body)

  # Inject the query counter JS before the closing </body> tag
  doc.at('body').add_child(injected_html)

  doc.to_html
end