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: www.martinfowler.com/eaaCatalog/identityMap.html

Instance Method Summary collapse

Constructor Details

#initializeIdentityMap

Returns a new instance of IdentityMap.



9
10
11
12
13
# File 'lib/data_mapper/identity_map.rb', line 9

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.



36
37
38
# File 'lib/data_mapper/identity_map.rb', line 36

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

#delete(instance) ⇒ Object

Remove an instance from the IdentityMap.



31
32
33
# File 'lib/data_mapper/identity_map.rb', line 31

def delete(instance)
  @cache[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.



17
18
19
# File 'lib/data_mapper/identity_map.rb', line 17

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

#set(instance) ⇒ Object

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



23
24
25
26
27
28
# File 'lib/data_mapper/identity_map.rb', line 23

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[instance.class][instance_key] = instance
end