Class: DataMapper::IdentityMap

Inherits:
Object
  • Object
show all
Defined in:
lib/data_mapper/identity_map.rb

Overview

Tracks objects to help ensure that each object gets loaded only once. See: http://www.martinfowler.com/eaaCatalog/identityMap.html

Instance Method Summary collapse

Constructor Details

#initializeIdentityMap

Returns a new instance of IdentityMap.



7
8
9
10
11
# File 'lib/data_mapper/identity_map.rb', line 7

def initialize
  # WeakHash is much more expensive, and not necessary if the IdentityMap is tied to Session instead of Database.
  # @cache = Hash.new { |h,k| h[k] = Support::WeakHash.new }
  @cache = Hash.new { |h,k| h[k] = Hash.new }
end

Instance Method Details

#clear!(klass) ⇒ Object

Clears a particular set of classes from the IdentityMap.



34
35
36
# File 'lib/data_mapper/identity_map.rb', line 34

def clear!(klass)
  @cache.delete(klass)
end

#delete(instance) ⇒ Object

Remove an instance from the IdentityMap.



29
30
31
# File 'lib/data_mapper/identity_map.rb', line 29

def delete(instance)
  @cache[mapped_class(instance.class)].delete(instance.key)
end

#get(klass, key) ⇒ Object

Pass a Class and a key, and to retrieve an instance. If the instance isn't found, nil is returned.



15
16
17
# File 'lib/data_mapper/identity_map.rb', line 15

def get(klass, key)
  @cache[mapped_class(klass)][key]
end

#set(instance) ⇒ Object

Pass an instance to add it to the IdentityMap. The instance must have an assigned key.



21
22
23
24
25
26
# File 'lib/data_mapper/identity_map.rb', line 21

def set(instance)
  instance_key = instance.key
  raise "Can't store an instance with a nil key in the IdentityMap" if instance_key.nil?
  
  @cache[mapped_class(instance.class)][instance_key] = instance
end