Sha256: f3ff2950b420f802b75d47bd21eecd9833f477ed885b1373849b3f4bfb26bd08

Contents?: true

Size: 1.34 KB

Versions: 6

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

module Goldiloader
  module AssociationLoader
    extend self

    def load(model, association_name)
      models = model.auto_include_context.models.select do |peer|
        load?(peer, association_name)
      end

      eager_load(models, association_name)
    end

    private

    def eager_load(models, association_name)
      ::ActiveRecord::Associations::Preloader.new.preload(models, [association_name])
    end

    def first_model_with_association(models, association_name)
      models.find { |model| has_association?(model, association_name) }
    end

    def associated_models(models, association_name)
      # We can't just do model.send(association_name) because the association method may have been
      # overridden
      models.map { |model| model.association(association_name).target }.flatten.compact.uniq
    end

    def load?(model, association_name)
      # Need to make sure the model actually has the association which won't always
      # be the case in STI hierarchies e.g. only a subclass might have the association
      has_association?(model, association_name) &&
        model.association(association_name).auto_include?
    end

    def has_association?(model, association_name) # rubocop:disable Naming/PredicateName
      model.class.reflect_on_association(association_name).present?
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
goldiloader-3.1.1 lib/goldiloader/association_loader.rb
goldiloader-3.1.0 lib/goldiloader/association_loader.rb
goldiloader-3.0.3 lib/goldiloader/association_loader.rb
goldiloader-3.0.2 lib/goldiloader/association_loader.rb
goldiloader-3.0.1 lib/goldiloader/association_loader.rb
goldiloader-3.0.0 lib/goldiloader/association_loader.rb