diff --git a/lib/mongoid/persistence_context.rb b/lib/mongoid/persistence_context.rb index 1f7ea96d6e..34d82fce01 100644 --- a/lib/mongoid/persistence_context.rb +++ b/lib/mongoid/persistence_context.rb @@ -117,12 +117,15 @@ def database_name def client @client ||= begin client = Clients.with_name(client_name) + options = client_options + if database_name_option client = client.use(database_name) + options = options.except(:database, 'database') end - unless client_options.empty? - client = client.with(client_options) - end + + client = client.with(options) unless options.empty? + client end end diff --git a/spec/mongoid/clients/options_spec.rb b/spec/mongoid/clients/options_spec.rb index 6260fefe65..23a7a03de7 100644 --- a/spec/mongoid/clients/options_spec.rb +++ b/spec/mongoid/clients/options_spec.rb @@ -27,7 +27,7 @@ let(:options) { { database: 'other' } } it 'sets the options on the client' do - expect(persistence_context.client.options['database']).to eq(options[:database]) + expect(persistence_context.client.options['database'].to_s).to eq(options[:database].to_s) end it 'does not set the options on class level' do @@ -319,7 +319,7 @@ end it 'sets the options on the client' do - expect(persistence_context.client.options['database']).to eq(options[:database]) + expect(persistence_context.client.options['database'].to_s).to eq(options[:database].to_s) end it 'does not set the options on instance level' do diff --git a/spec/mongoid/persistence_context_spec.rb b/spec/mongoid/persistence_context_spec.rb index 93676dfabf..ecbc95bd80 100644 --- a/spec/mongoid/persistence_context_spec.rb +++ b/spec/mongoid/persistence_context_spec.rb @@ -536,6 +536,20 @@ end end end + + context 'when the database is specified as a proc' do + let(:options) { { database: ->{ 'other' } } } + + after { persistence_context.client.close } + + it 'evaluates the proc' do + expect(persistence_context.database_name).to eq(:other) + end + + it 'does not pass the proc to the client' do + expect(persistence_context.client.database.name).to eq('other') + end + end end describe '#client' do @@ -608,6 +622,23 @@ end end + context 'when the client is set as a proc in the storage options' do + let(:options) { {} } + + before do + Band.store_in client: ->{ :alternative } + end + + after do + persistence_context.client.close + Band.store_in client: nil + end + + it 'uses the client option' do + expect(persistence_context.client).to eq(Mongoid::Clients.with_name(:alternative)) + end + end + context 'when there is no client option set' do let(:options) do