Sha256: d89ad92b41a0f03e28d9b6fd8c1d026bedf2789547d61080f436eded8103e375
Contents?: true
Size: 1.77 KB
Versions: 1
Compression:
Stored size: 1.77 KB
Contents
module JitPreloadExtension extend ActiveSupport::Concern included do attr_accessor :jit_preloader attr_accessor :jit_n_plus_one_tracking attr_accessor :jit_preload_aggregates def reload(*args) self.jit_preload_aggregates = {} super end end class_methods do delegate :jit_preload, to: :all def has_many_aggregate(assoc, name, aggregate, field, default: 0) method_name = "#{assoc}_#{name}" define_method(method_name) do |conditions={}| self.jit_preload_aggregates ||= {} key = "#{method_name}|#{conditions.sort.hash}" return jit_preload_aggregates[key] if jit_preload_aggregates.key?(key) if jit_preloader reflection = association(assoc).reflection primary_ids = jit_preloader.records.collect{|r| r[reflection.active_record_primary_key] } klass = reflection.klass association_scope = klass association_scope = association_scope.instance_exec(&reflection.scope).reorder(nil) if reflection.scope conditions[reflection.foreign_key] = primary_ids preloaded_data = Hash[association_scope .where(conditions) .group(reflection.foreign_key) .send(aggregate, field) ] jit_preloader.records.each do |record| record.jit_preload_aggregates ||= {} record.jit_preload_aggregates[key] = preloaded_data[record.id] || default end else self.jit_preload_aggregates[key] = send(assoc).where(conditions).send(aggregate, field) || default end jit_preload_aggregates[key] end end end end ActiveRecord::Base.send(:include, JitPreloadExtension)
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
jit_preloader-0.0.8 | lib/jit_preloader/active_record/base.rb |