Skip to content

Commit

Permalink
Merge fe6adda into a43eea8
Browse files Browse the repository at this point in the history
  • Loading branch information
mrkamel committed May 27, 2020
2 parents a43eea8 + fe6adda commit 5a13c7c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/dynamoid/criteria/chain.rb
Expand Up @@ -176,6 +176,21 @@ def count
end
end

# Returns the first item matching the criteria.
#
# Post.where(links_count: 2).first
#
# Applies `record_limit(1)` to ensure only a single record is fetched.
#
# If used without criteria it just returns the first item of some arbitrary order.
#
# Post.first
#
# @return [Model|nil]
def first
record_limit(1).to_a.first
end

# Returns the last item matching the criteria.
#
# Post.where(links_count: 2).last
Expand Down
36 changes: 36 additions & 0 deletions spec/dynamoid/criteria/chain_spec.rb
Expand Up @@ -1430,6 +1430,42 @@ def request_params
end
end

describe '#first' do
let(:model) do
new_class partition_key: :name do
range :age, :integer
end
end

it 'applies a record_limit' do
chain = Dynamoid::Criteria::Chain.new(Address)
expect(chain).to receive(:record_limit).with(1)
chain = chain.first
end

it 'returns nil if no matching document is present' do
model.create(name: 'Bob', age: 5)

expect(model.where(name: 'Alice').first).to be_nil
end

it 'returns the first document with regards to the sort order' do
customer1 = model.create(name: 'Bob', age: 5)
customer2 = model.create(name: 'Bob', age: 9)
customer3 = model.create(name: 'Bob', age: 12)

expect(model.first.age).to eq(5)
end

it 'returns the first document matching the criteria and with regards to the sort order' do
customer1 = model.create(name: 'Bob', age: 4)
customer3 = model.create(name: 'Alice', age: 6)
customer4 = model.create(name: 'Alice', age: 8)

expect(model.where(name: 'Alice').first.age).to eq(6)
end
end

describe '#count' do
describe 'Query vs Scan' do
it 'Scans when query is empty' do
Expand Down

0 comments on commit 5a13c7c

Please sign in to comment.