Sha256: fec58a743bcb7a14f56fce1130517d217400aaf3afac02e9ae0530c2c9177a75

Contents?: true

Size: 1.27 KB

Versions: 3

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true
module IdentityCache
  module Cached
    module EmbeddedFetching
      private

      def fetch_embedded(records)
        fetch_embedded_async(LoadStrategy::Eager, records) {}
      end

      def fetch_embedded_async(load_strategy, records)
        return yield if embedded_fetched?(records)

        klass = reflection.active_record
        cached_associations = klass.send(:embedded_associations)

        return yield if cached_associations.empty?

        return yield unless klass.primary_cache_index_enabled

        load_strategy.load_multi(klass.cached_primary_index, records.map(&:id)) do |cached_records_by_id|
          cached_associations.each_value do |cached_association|
            records.each do |record|
              next unless (cached_record = cached_records_by_id[record.id])
              cached_value = cached_association.read(cached_record)
              cached_association.write(record, cached_value)
            end
          end

          yield
        end
      end

      def embedded_fetched?(records)
        # NOTE: Assume all records are the same, so just check the first one.
        record = records.first
        record.association(name).loaded? || record.instance_variable_defined?(records_variable_name)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
identity_cache-1.1.0 lib/identity_cache/cached/embedded_fetching.rb
identity_cache-1.0.1 lib/identity_cache/cached/embedded_fetching.rb
identity_cache-1.0.0 lib/identity_cache/cached/embedded_fetching.rb