Class: ActiveRecordStats::RackMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_stats/rack_middleware.rb

Constant Summary collapse

ENV_KEY =

The location in the Rack ‘env` where ActionDispatch stores its `parameters` value. This may change across Rails versions, but I am not aware of any more reliable means of retrieving it.

'action_dispatch.request.parameters'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ RackMiddleware

Returns a new instance of RackMiddleware.



13
14
15
# File 'lib/active_record_stats/rack_middleware.rb', line 13

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
43
44
45
46
47
48
49
50
# File 'lib/active_record_stats/rack_middleware.rb', line 17

def call(env)
  totals  = {}
  db_time = 0

  gather_sql = ->(_name, _started_at, _finished_at, _unique_id, payload) {
    return if payload[:name] == 'SCHEMA' || payload[:sql].blank?
    return unless type = ActiveRecordStats.statement_type(payload[:sql])
    totals[type] ||= 0
    totals[type] += 1
  }

  gather_runtime = ->(_name, _started_at, _finished_at, _unique_id, payload) {
    db_time = payload.fetch(:db_runtime) { 0 }
  }

  subs = [
    ActiveSupport::Notifications.subscribe('sql.active_record', &gather_sql),
    ActiveSupport::Notifications.subscribe('process_action.action_controller', &gather_runtime)
  ]

  @app.call(env)

ensure
  subs.each do |sub|
    ActiveSupport::Notifications.unsubscribe(sub)
  end

  request_params = env[ENV_KEY]
  if request_params && controller = request_params['controller']
    controller = controller.gsub('/', '__')
    action = request_params['action']
    emit(controller, action, db_time, totals.dup)
  end
end