@@ -189,8 +189,7 @@ class << self
189
189
#
190
190
# @return [ Mongoid::PersistenceContext ] The persistence context for the object.
191
191
def set ( object , options_or_context )
192
- key = "[mongoid][#{ object . object_id } ]:context"
193
- existing_context = Thread . current [ key ]
192
+ existing_context = get_context ( object )
194
193
existing_options = if existing_context
195
194
existing_context . options
196
195
else
@@ -201,7 +200,7 @@ def set(object, options_or_context)
201
200
end
202
201
new_options = existing_options . merge ( options_or_context )
203
202
context = PersistenceContext . new ( object , new_options )
204
- Thread . current [ key ] = context
203
+ store_context ( object , context )
205
204
end
206
205
207
206
# Get the persistence context for a particular class or model instance.
@@ -213,7 +212,7 @@ def set(object, options_or_context)
213
212
#
214
213
# @return [ Mongoid::PersistenceContext ] The persistence context for the object.
215
214
def get ( object )
216
- Thread . current [ "[mongoid][ #{ object . object_id } ]:context" ]
215
+ get_context ( object )
217
216
end
218
217
219
218
# Clear the persistence context for a particular class or model instance.
@@ -232,7 +231,44 @@ def clear(object, cluster = nil, original_context = nil)
232
231
end
233
232
end
234
233
ensure
235
- Thread . current [ "[mongoid][#{ object . object_id } ]:context" ] = original_context
234
+ store_context ( object , original_context )
235
+ end
236
+
237
+ private
238
+
239
+ # Key to store persistence contexts in the thread local storage.
240
+ #
241
+ # @api private
242
+ PERSISTENCE_CONTEXT_KEY = :"[mongoid]:persistence_context"
243
+
244
+ # Get the persistence context for a given object from the thread local
245
+ # storage.
246
+ #
247
+ # @param [ Object ] object Object to get the persistance context for.
248
+ #
249
+ # @return [ Mongoid::PersistenceContext | nil ] The persistence context
250
+ # for the object if previously stored, otherwise nil.
251
+ #
252
+ # @api private
253
+ def get_context ( object )
254
+ Thread . current [ PERSISTENCE_CONTEXT_KEY ] ||= { }
255
+ Thread . current [ PERSISTENCE_CONTEXT_KEY ] [ object . object_id ]
256
+ end
257
+
258
+ # Store persistence context for a given object in the thread local
259
+ # storage.
260
+ #
261
+ # @param [ Object ] object Object to store the persistance context for.
262
+ # @param [ Mongoid::PersistenceContext ] context Context to store
263
+ #
264
+ # @api private
265
+ def store_context ( object , context )
266
+ if context . nil?
267
+ Thread . current [ PERSISTENCE_CONTEXT_KEY ] &.delete ( object . object_id )
268
+ else
269
+ Thread . current [ PERSISTENCE_CONTEXT_KEY ] ||= { }
270
+ Thread . current [ PERSISTENCE_CONTEXT_KEY ] [ object . object_id ] = context
271
+ end
236
272
end
237
273
end
238
274
end
0 commit comments