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

Defined in:
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.



42
43
44
# File 'lib/sequel/plugins/identity_map.rb', line 42

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.



48
49
50
# File 'lib/sequel/plugins/identity_map.rb', line 48

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.



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

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.



72
73
74
75
76
77
78
79
80
# File 'lib/sequel/plugins/identity_map.rb', line 72

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