Sha256: 8888bca24d56f2dcef215bb2039df4187ba86fa039d7cd8aeb64942c45d477f4

Contents?: true

Size: 1.77 KB

Versions: 2

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true
module IdentityCache
  module Cached
    module Recursive
      class Association < Cached::Association # :nodoc:
        def initialize(name, reflection:)
          super
          @dehydrated_variable_name = :"@dehydrated_#{name}"
        end

        attr_reader :dehydrated_variable_name

        def build
          reflection.active_record.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
            def #{cached_accessor_name}
              fetch_recursively_cached_association(
                :#{records_variable_name},
                :#{dehydrated_variable_name},
                :#{name}
              )
            end
          RUBY

          ParentModelExpiration.add_parent_expiry_hook(self)
        end

        def read(record)
          record.public_send(cached_accessor_name)
        end

        def write(record, records)
          record.instance_variable_set(records_variable_name, records)
        end

        def clear(record)
          if record.instance_variable_defined?(records_variable_name)
            record.remove_instance_variable(records_variable_name)
          end
        end

        def fetch(records)
          fetch_async(LoadStrategy::Eager, records) { |child_records| child_records }
        end

        def fetch_async(load_strategy, records)
          fetch_embedded_async(load_strategy, records) do
            yield records.flat_map(&cached_accessor_name).tap(&:compact!)
          end
        end

        def embedded_by_reference?
          false
        end

        def embedded_recursively?
          true
        end

        private

        def embedded_fetched?(records)
          record = records.first
          super || record.instance_variable_defined?(dehydrated_variable_name)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
identity_cache-1.0.1 lib/identity_cache/cached/recursive/association.rb
identity_cache-1.0.0 lib/identity_cache/cached/recursive/association.rb