Class: JitPreloader::Preloader

Inherits:
ActiveRecord::Associations::Preloader
  • Object
show all
Defined in:
lib/jit_preloader/preloader.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#recordsObject

Returns the value of attribute records.



4
5
6
# File 'lib/jit_preloader/preloader.rb', line 4

def records
  @records
end

Class Method Details

._load(args) ⇒ Object



57
58
59
# File 'lib/jit_preloader/preloader.rb', line 57

def self._load(args)
  nil
end

.attach(records) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/jit_preloader/preloader.rb', line 7

def self.attach(records)
  new(records: records.dup, associations: nil).tap do |loader|
    records.each do |record|
      record.jit_preloader = loader
    end
  end
end

Instance Method Details

#_dump(level) ⇒ Object

We do not want the jit_preloader to be dumpable If you dump a ActiveRecord::Base object that has a jit_preloader instance variable you will also end up dumping all of the records the preloader has reference to. Imagine getting N objects from a query and dumping each one of those into a cache each object would dump N+1 objects which means you’ll end up storing O(N^2) memory. Thats no good. So instead, we will just nullify the jit_preloader on load



53
54
55
# File 'lib/jit_preloader/preloader.rb', line 53

def _dump(level)
  ""
end

#jit_preload(associations) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/jit_preloader/preloader.rb', line 15

def jit_preload(associations)
  # It is possible that the records array has multiple different classes (think single table inheritance).
  # Thus, it is possible that some of the records don't have an association.
  records_with_association = records.reject{|r| r.class.reflect_on_association(associations).nil? }

  # Some of the records may already have the association loaded and we should not load them again
  records_requiring_loading = records_with_association.select{|r| !r.association(associations).loaded? }

  self.class.new(records: records_requiring_loading, associations: associations).call
end