Sha256: 97043c73fe399731751321fa3fe23f8ca4b7fd1489bbb2aac97486b1bc568d5a

Contents?: true

Size: 1.61 KB

Versions: 7

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

module Dynamoid
  module IdentityMap
    extend ActiveSupport::Concern

    def self.clear
      Dynamoid.included_models.each { |m| m.identity_map.clear }
    end

    module ClassMethods
      def identity_map
        @identity_map ||= {}
      end

      def from_database(attrs = {})
        return super if identity_map_off?

        key = identity_map_key(attrs)
        document = identity_map[key]

        if document.nil?
          document = super
          identity_map[key] = document
        else
          document.load(attrs)
        end

        document
      end

      def find_by_id(id, options = {})
        return super if identity_map_off?

        key = id.to_s

        if range_key = options[:range_key]
          key += "::#{range_key}"
        end

        identity_map[key] || super
      end

      def identity_map_key(attrs)
        key = attrs[hash_key].to_s
        key += "::#{attrs[range_key]}" if range_key
        key
      end

      def identity_map_on?
        Dynamoid::Config.identity_map
      end

      def identity_map_off?
        !identity_map_on?
      end
    end

    def identity_map
      self.class.identity_map
    end

    def save(*args)
      return super if self.class.identity_map_off?

      if result = super
        identity_map[identity_map_key] = self
      end
      result
    end

    def delete
      return super if self.class.identity_map_off?

      identity_map.delete(identity_map_key)
      super
    end

    def identity_map_key
      key = hash_key.to_s
      key += "::#{range_value}" if self.class.range_key
      key
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
dynamoid-3.5.0 lib/dynamoid/identity_map.rb
dynamoid-3.4.1 lib/dynamoid/identity_map.rb
dynamoid-3.4.0 lib/dynamoid/identity_map.rb
dynamoid-3.3.0 lib/dynamoid/identity_map.rb
dynamoid-3.2.0 lib/dynamoid/identity_map.rb
dynamoid-3.1.0 lib/dynamoid/identity_map.rb
dynamoid-3.0.0 lib/dynamoid/identity_map.rb