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 28 28: def identity_map 29: Thread.current[:sequel_identity_map] 30: 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 34 34: def identity_map_key(pk) 35: "#{self}:#{pk ? Array(pk).join(',') : "nil:#{rand}"}" 36: 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 45 45: def load(row) 46: return super unless idm = identity_map 47: if o = idm[identity_map_key(Array(primary_key).map{|x| row[x]})] 48: o.merge_db_update(row) 49: else 50: o = super 51: idm[identity_map_key(o.pk)] = o 52: end 53: o 54: 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 58 58: def with_identity_map 59: return yield if identity_map 60: begin 61: self.identity_map = {} 62: yield 63: ensure 64: self.identity_map = nil 65: end 66: end