Skip to content

Commit

Permalink
fix each method to unify iteration in pages or common iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
diegosenarruzza committed Dec 14, 2020
1 parent 60db9e6 commit 0e2d795
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
22 changes: 13 additions & 9 deletions lib/rasti/db/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,11 @@ def all
end
alias_method :to_a, :all

def each(&block)
all.each(&block)
end

def each_in_pages(size:, &block)
dataset.each_page(size) do |page|
page.each do |row|
block.call build_model(row)
end
def each(size:nil, &block)
if size.nil?
all.each(&block)
else
each_batch size: size, &block
end
end

Expand Down Expand Up @@ -171,6 +167,14 @@ def chainable(&block)
build_query dataset: instance_eval(&block)
end

def each_batch(size:, &block)
dataset.each_page(size) do |page|
page.each do |row|
block.call build_model(row)
end
end
end

def with_related(relation_name, primary_keys)
ds = collection_class.relations[relation_name].apply_filter environment, dataset, primary_keys
build_query dataset: ds
Expand Down
30 changes: 23 additions & 7 deletions spec/query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,31 @@
users_query.detect(id: 3).must_equal User.new(id: 3, name: 'User 3')
end

it 'Each in pages' do
user_pages = []
users_query.each_in_pages(size: 2) do | page |
user_pages << page
describe 'Each' do

it 'without size' do
users = []

users_query.each do | user |
users << user
end
users.size.must_equal 10
users.each_with_index do | user, i |
user.must_equal User.new(id: i+1, name: "User #{i+1}")
end
end
user_pages.size.must_equal 10
user_pages.each_with_index do | user_page, i |
user_page.must_equal User.new(id: i+1, name: "User #{i+1}")

it 'with size' do
users = []
users_query.each(size: 2) do | user |
users << user
end
users.size.must_equal 10
users.each_with_index do | user, i |
user.must_equal User.new(id: i+1, name: "User #{i+1}")
end
end

end

it 'Each page' do
Expand Down

0 comments on commit 0e2d795

Please sign in to comment.