Sha256: 4d2d39496344b9d03af47f944566325cc92c62ebde5af5aceee11b41683730f6

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 KB

Contents

module JitPreloader
  class Preloader < ActiveRecord::Associations::Preloader

    attr_accessor :records

    def self.attach(records)
      new.tap do |loader|
        loader.records = records
        records.each do |record|
          record.jit_preloader = loader
        end
      end
    end

    def jit_preload(association)
      # 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(association).nil? }
      preload records_with_association, association
    end

    # 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
    def _dump(level)
      ""
    end

    def self._load(args)
      nil
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
jit_preloader-0.0.6 lib/jit_preloader/preloader.rb
jit_preloader-0.0.5 lib/jit_preloader/preloader.rb
jit_preloader-0.0.4 lib/jit_preloader/preloader.rb
jit_preloader-0.0.3 lib/jit_preloader/preloader.rb