diff --git a/lib/mongoid/persistence_context.rb b/lib/mongoid/persistence_context.rb index 0150be500b..0fe9dd6d44 100644 --- a/lib/mongoid/persistence_context.rb +++ b/lib/mongoid/persistence_context.rb @@ -143,6 +143,20 @@ def ==(other) options == other.options end + # Whether the client of the context can be reused later, and therefore should + # not be closed. + # + # If the persistence context is requested with :client option only, it means + # that the context should use a client configured in mongoid.yml. + # Such clients should not be closed when the context is cleared since they + # will be reused later. + # + # @return [ true | false ] True if client can be reused, otherwise false. + # + # @api private + def reusable_client? + @options.keys == [:client] + end private def set_options!(opts) @@ -238,7 +252,7 @@ def get(object) def clear(object, cluster = nil, original_context = nil) if context = get(object) unless cluster.nil? || context.cluster.equal?(cluster) - context.client.close + context.client.close unless context.reusable_client? end end ensure