Class: PredictiveLoad::Loader

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

Overview

Predictive loader

Usage: ActiveRecord::Relation.collection_observer = LazyLoader

Direct Known Subclasses

Watcher

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(records) ⇒ Loader



13
14
15
# File 'lib/predictive_load/loader.rb', line 13

def initialize(records)
  @records = records
end

Class Method Details

.observe(records) ⇒ Object



9
10
11
# File 'lib/predictive_load/loader.rb', line 9

def self.observe(records)
  new(records).observe
end

Instance Method Details

#all_records_will_likely_load_association?(association_name) ⇒ Boolean



31
32
33
34
35
36
37
# File 'lib/predictive_load/loader.rb', line 31

def all_records_will_likely_load_association?(association_name)
  if defined?(Mocha) && association_name.to_s.index('_stub_')
    false
  else
    true
  end
end

#loading_association(record, association) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/predictive_load/loader.rb', line 23

def loading_association(record, association)
  association_name = association.reflection.name

  if all_records_will_likely_load_association?(association_name) && supports_preload?(association)
    preload(association_name)
  end
end

#observeObject



17
18
19
20
21
# File 'lib/predictive_load/loader.rb', line 17

def observe
  records.each do |record|
    record.collection_observer = self
  end
end

#supports_preload?(association) ⇒ Boolean



39
40
41
42
# File 'lib/predictive_load/loader.rb', line 39

def supports_preload?(association)
  return false if association.reflection.options[:conditions].respond_to?(:to_proc)
  true
end