Module: Sequel::Plugins::IdentityMap::ClassMethods

Defined in:
lib/sequel/lib/sequel/plugins/identity_map.rb

Instance Method Summary collapse

Instance Method Details

#identity_mapObject

Returns the current thread-local identity map. Should be a hash if there is an active identity map, and nil otherwise.


28
29
30
# File 'lib/sequel/lib/sequel/plugins/identity_map.rb', line 28

def identity_map
  Thread.current[:sequel_identity_map]
end

#identity_map_key(pk) ⇒ Object

The identity map key for an object of the current class with the given pk. May not always be correct for a class which uses STI.


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

def identity_map_key(pk)
  "#{self}:#{pk ? Array(pk).join(',') : "nil:#{rand}"}"
end

#load(row) ⇒ Object

If the identity map is in use, check it for a current copy of the object. If a copy does not exist, create a new object and add it to the identity map. If a copy exists, add any values in the given row that aren't currently in the object to the object's values. This allows you to only request certain fields in an initial query, make modifications to some of those fields and request other, potentially overlapping fields in a new query, and not have the second query override fields you modified.


45
46
47
48
49
50
51
52
53
54
# File 'lib/sequel/lib/sequel/plugins/identity_map.rb', line 45

def load(row)
  return super unless idm = identity_map
  if o = idm[identity_map_key(Array(primary_key).map{|x| row[x]})]
    o.merge_db_update(row)
  else
    o = super
    idm[identity_map_key(o.pk)] = o
  end
  o
end

#with_identity_mapObject

Take a block and inside that block use an identity map to ensure a 1-1 correspondence of objects to the database row they represent.


58
59
60
61
62
63
64
65
66
# File 'lib/sequel/lib/sequel/plugins/identity_map.rb', line 58

def with_identity_map
  return yield if identity_map
  begin
    self.identity_map = {}
    yield
  ensure
    self.identity_map = nil
  end
end