From 65ccfbc78ddca76899101d50f94afe946d8cbcc7 Mon Sep 17 00:00:00 2001 From: johnnyshields <27655+johnnyshields@users.noreply.github.com> Date: Sun, 27 Aug 2023 16:28:19 +0900 Subject: [PATCH] Get rid of extra loop --- lib/mongoid/contextual/mongo.rb | 2 +- spec/mongoid/contextual/mongo_spec.rb | 28 +++++++++++++-------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lib/mongoid/contextual/mongo.rb b/lib/mongoid/contextual/mongo.rb index adc2f042d7..235c6febea 100644 --- a/lib/mongoid/contextual/mongo.rb +++ b/lib/mongoid/contextual/mongo.rb @@ -811,7 +811,6 @@ def load_async def update_documents(attributes, method = :update_one, opts = {}) return false unless attributes - attributes = Hash[attributes.map { |k, v| [klass.database_field_name(k.to_s), v] }] view.send(method, prepare_atomic_updates(klass, attributes), opts) end @@ -1076,6 +1075,7 @@ def retrieve_nth_to_last_with_limit(n, limit) # @return [ Hash ] The prepared atomic updates. def prepare_atomic_updates(klass, attributes) attributes.each_pair.with_object({}) do |(key, value), atomic_updates| + key = klass.database_field_name(key) if key.to_s.start_with?('$') value = value.each_with_object({}) do |(key2, value2), hash| key2 = klass.database_field_name(key2) diff --git a/spec/mongoid/contextual/mongo_spec.rb b/spec/mongoid/contextual/mongo_spec.rb index 138ea450b2..76acf6df4e 100644 --- a/spec/mongoid/contextual/mongo_spec.rb +++ b/spec/mongoid/contextual/mongo_spec.rb @@ -4573,9 +4573,9 @@ end describe '#prepare_atomic_updates' do - let(:instance) { described_class.new(Band.where(name: 'Depeche Mode')) } + subject(:updates) { instance.send(:prepare_atomic_updates, Band, hash) } - subject { instance.send(:prepare_atomic_updates, Band, hash) } + let(:instance) { described_class.new(Band.where(name: 'Depeche Mode')) } context 'when the hash already contains the key' do @@ -4585,10 +4585,10 @@ end it 'moves the non hash values under the provided key' do - expect(subject).to eq({ - '$set' => { 'name' => 'Tool', likes: 10 }, - '$inc' => { 'plays' => 1 } - }) + expect(updates).to eq({ + '$set' => { 'name' => 'Tool', 'likes' => 10 }, + '$inc' => { 'plays' => 1 } + }) end end @@ -4598,10 +4598,10 @@ end it 'moves the non hash values under the provided key' do - expect(subject).to eq({ - '$set' => { likes: 10, 'name' => 'Tool' }, - '$inc' => { 'plays' => 1 } - }) + expect(updates).to eq({ + '$set' => { 'likes' => 10, 'name' => 'Tool' }, + '$inc' => { 'plays' => 1 } + }) end end end @@ -4612,10 +4612,10 @@ end it 'moves the non hash values under the provided key' do - expect(subject).to eq({ - '$set' => { likes: 10, name: 'Tool' }, - '$inc' => { 'plays' => 1 } - }) + expect(updates).to eq({ + '$set' => { 'likes' => 10, 'name' => 'Tool' }, + '$inc' => { 'plays' => 1 } + }) end end end