diff --git a/.gitignore b/.gitignore index d87d4be..2de3904 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ spec/reports test/tmp test/version_tmp tmp +.idea diff --git a/CHANGELOG.md b/CHANGELOG.md index a0ecb07..74a75db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Not released +- Change `.first` to not query the API if records have already been retrieved (https://github.com/Beyond-Finance/active_force/pull/73) + ## 0.19.0 - Bulk API methods. (https://github.com/Beyond-Finance/active_force/pull/65) diff --git a/lib/active_force/query.rb b/lib/active_force/query.rb index 2afb02a..642651d 100644 --- a/lib/active_force/query.rb +++ b/lib/active_force/query.rb @@ -78,7 +78,15 @@ def find id end def first - limit 1 + if @records + clone_and_set_instance_variables( + size: 1, + records: [@records.first], + decorated_records: [@decorated_records&.first] + ) + else + limit(1) + end end def last(limit = 1) @@ -126,9 +134,9 @@ def build_offset def clone_and_set_instance_variables instance_variable_hash={} clone = self.clone - clone.instance_variable_set(:@decorated_records, nil) - clone.instance_variable_set(:@records, nil) - instance_variable_hash.each { |k,v| clone.instance_variable_set("@#{k.to_s}", v) } + { decorated_records: nil, records: nil } + .merge(instance_variable_hash) + .each { |k,v| clone.instance_variable_set("@#{k.to_s}", v) } clone end end diff --git a/spec/active_force/query_spec.rb b/spec/active_force/query_spec.rb index b3c187d..e59f4dc 100644 --- a/spec/active_force/query_spec.rb +++ b/spec/active_force/query_spec.rb @@ -165,6 +165,22 @@ expect(query.to_s).to eq "SELECT Id, name, etc FROM table_name" expect(new_query.to_s).to eq 'SELECT Id, name, etc FROM table_name LIMIT 1' end + + it "does not query if records have already been fetched" do + query = ActiveForce::Query.new 'table_name' + query.instance_variable_set(:@records, %w[foo bar]) + query.instance_variable_set(:@decorated_records, %w[foo bar]) + expect(query).not_to receive(:limit) + expect(query).to receive(:clone_and_set_instance_variables).with(size: 1, records: ['foo'], decorated_records: ['foo']) + query.first + end + + it 'queries the api if it has not been queried yet' do + query = ActiveForce::Query.new 'table_name' + query.instance_variable_set(:@records, nil) + expect(query).to receive(:limit) + query.first + end end describe '.last' do