Module | Sequel::Plugins::IdentityMap::ClassMethods |
In: |
lib/sequel/plugins/identity_map.rb
|
Returns the current thread-local identity map. Should be a hash if there is an active identity map, and nil otherwise.
# File lib/sequel/plugins/identity_map.rb, line 37 37: def identity_map 38: Thread.current[:sequel_identity_map] 39: end
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.
# File lib/sequel/plugins/identity_map.rb, line 43 43: def identity_map_key(pk) 44: "#{self}:#{pk ? Array(pk).join(',') : "nil:#{rand}"}" 45: end
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.
# File lib/sequel/plugins/identity_map.rb, line 54 54: def load(row) 55: return super unless idm = identity_map 56: if o = idm[identity_map_key(Array(primary_key).map{|x| row[x]})] 57: o.merge_db_update(row) 58: else 59: o = super 60: idm[identity_map_key(o.pk)] = o 61: end 62: o 63: end
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.
# File lib/sequel/plugins/identity_map.rb, line 67 67: def with_identity_map 68: return yield if identity_map 69: begin 70: self.identity_map = {} 71: yield 72: ensure 73: self.identity_map = nil 74: end 75: end