Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion lib/mongoid/persistence_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,21 @@ 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)
Expand Down Expand Up @@ -211,7 +226,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
Expand Down
30 changes: 30 additions & 0 deletions spec/mongoid/clients_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,36 @@
end
end
end

context 'when requesting named client' do
let(:secondary_client) do
double(Mongo::Client).tap do |client|
allow(client).to receive(:cluster).and_return(double("cluster"))
end
end

before do
expect(Mongoid::Clients::Factory).to receive(:create)
.with(:secondary)
.and_return(secondary_client)
end

after do
Mongoid::Clients.clients.delete(:secondary)
end

it 'does not close the client' do
expect(secondary_client).not_to receive(:close)

Band.with(client: :default) do |klass|
klass.mongo_client
end

Band.with(client: :secondary) do |klass|
klass.mongo_client
end
end
end
end

context "when overriding the default database" do
Expand Down
27 changes: 26 additions & 1 deletion spec/mongoid/persistence_context_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
end
end


describe '.get' do

let(:options) do
Expand Down Expand Up @@ -134,6 +133,32 @@
end
end
end

context 'with reusable client' do
let(:options) do
{client: :some_client}
end

let(:cluster) do
double(Mongo::Cluster)
end

let(:client) do
double(Mongo::Client).tap do |client|
allow(client).to receive(:cluster).and_return(cluster)
end
end

before do
expect(Mongoid::Clients).to receive(:with_name).with(:some_client).and_return(client)
expect(client).not_to receive(:close)
end

it 'does not close the client' do
described_class.set(object, options)
described_class.clear(object, cluster.dup)
end
end
end

describe '#initialize' do
Expand Down