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 41 41: def identity_map 42: Thread.current[:sequel_identity_map] 43: 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 47 47: def identity_map_key(pk) 48: "#{self}:#{pk ? Array(pk).join(',') : "nil:#{rand}"}" 49: 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 58 58: def load(row) 59: return super unless idm = identity_map 60: if o = idm[identity_map_key(Array(primary_key).map{|x| row[x]})] 61: o.merge_db_update(row) 62: else 63: o = super 64: idm[identity_map_key(o.pk)] = o 65: end 66: o 67: 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 71 71: def with_identity_map 72: return yield if identity_map 73: begin 74: self.identity_map = {} 75: yield 76: ensure 77: self.identity_map = nil 78: end 79: end