Class: PredictiveLoad::Watcher

Inherits:
Loader
  • Object
show all
Defined in:
lib/predictive_load/watcher.rb

Overview

Provides N+1 detection / log mode.

Usage: ActiveRecord::Relation.collection_observer = PredictiveLoad::Watcher

Example output: predictive_load: detected n1 call on Comment#account predictive_load: expect to prevent 1 queries predictive_load: would preload with: SELECT ‘accounts`.* FROM `accounts` WHERE `accounts`.`id` IN (…) predictive_load: ----————-----------——----------------———---------——-------——-+ predictive_load: | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | predictive_load: ----————-----------——----------------———---------——-------——-+ predictive_load: | 1 | SIMPLE | accounts | const | PRIMARY | PRIMARY | 4 | const | 1 | | predictive_load: ----————-----------——----------------———---------——-------——-+ predictive_load: 1 row in set (0.00 sec) predictive_load: would have prevented all 1 queries

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Loader

observe, #observe

Constructor Details

#initialize(records) ⇒ Watcher

Returns a new instance of Watcher.



27
28
29
30
# File 'lib/predictive_load/watcher.rb', line 27

def initialize(records)
  super
  @loaded_associations = {}
end

Instance Attribute Details

#loaded_associationsObject (readonly)

Returns the value of attribute loaded_associations.



25
26
27
# File 'lib/predictive_load/watcher.rb', line 25

def loaded_associations
  @loaded_associations
end

Instance Method Details

#loading_association(record, association) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/predictive_load/watcher.rb', line 32

def loading_association(record, association)
  association_name = association.reflection.name
  return if !all_records_will_likely_load_association?(association_name)
  return if !supports_preload?(association)

  if loaded_associations.key?(association_name)
    log_query_plan(association_name)
  end

  increment_query_count(association_name)
end