Sha256: a9f8ebc9e35e581c087a40c5fafb73cdfa0bb5fc774c3557fa8a397a8bb40584

Contents?: true

Size: 1.73 KB

Versions: 11

Compression:

Stored size: 1.73 KB

Contents

module Dynamoid
  module IdentityMap
    extend ActiveSupport::Concern

    def self.clear
      models.each { |m| m.identity_map.clear }
    end

    def self.models
      Dynamoid::Config.included_models
    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

        if identity_map[key]
          identity_map[key]
        else
          super
        end
      end

      def identity_map_key(attrs)
        key = attrs[hash_key].to_s
        if range_key
          key += "::#{attrs[range_key]}"
        end
        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
      if self.class.range_key
        key += "::#{range_value}"
      end
      key
    end
  end
end

Version data entries

11 entries across 11 versions & 3 rubygems

Version Path
dynamoid-moda-0.7.2 lib/dynamoid/identity_map.rb
dynamoid-moda-0.7.1 lib/dynamoid/identity_map.rb
dynamoid-0.7.1 lib/dynamoid/identity_map.rb
dynamoid-0.7.0 lib/dynamoid/identity_map.rb
dynamoid-0.6.1 lib/dynamoid/identity_map.rb
dynamoid-0.6.0 lib/dynamoid/identity_map.rb
adept_dynamoid-0.6.0 lib/dynamoid/identity_map.rb
adept_dynamoid-0.5.0.8 lib/dynamoid/identity_map.rb
adept_dynamoid-0.5.0.7 lib/dynamoid/identity_map.rb
adept_dynamoid-0.5.0.6 lib/dynamoid/identity_map.rb
dynamoid-0.5.0 lib/dynamoid/identity_map.rb