Permalink
Browse files

Merge pull request #13201 from marcandre/find_in_batch_enumerator

`find_in_batches` now returns an `Enumerator`

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/relation/batches.rb
  • Loading branch information...
2 parents 2c964ac + 0aad463 commit fec1028d088294c30f568e46db3bbd054a9330ff @rafaelfranca rafaelfranca committed Jan 29, 2014
@@ -1,3 +1,8 @@
+* `find_in_batches` now returns an `Enumerator` when called without a block, so that it
+ can be chained with other `Enumerable` methods.
+
+ *Marc-André Lafortune*
+
* `enum` now raises on "dangerous" name conflicts
Dangerous name conflicts includes instance or class method conflicts
@@ -64,6 +64,14 @@ def find_each(options = {})
# group.each { |person| person.party_all_night! }
# end
#
+ # If you do not provide a block to #find_in_batches, it will return an Enumerator
+ # for chaining with other methods:
+ #
+ # Person.find_in_batches.with_index do |group, batch|
+ # puts "Processing group ##{batch}"
+ # group.each(&:recover_from_last_night!)
+ # end
+ #
# To be yielded each record one by one, use #find_each instead.
#
# ==== Options
@@ -88,6 +96,7 @@ def find_each(options = {})
# the batch sizes.
def find_in_batches(options = {})
options.assert_valid_keys(:start, :batch_size)
+ return to_enum(:find_in_batches, options) unless block_given?
relation = self
@@ -172,4 +172,17 @@ def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_
end
end
end
+
+ def test_find_in_batches_should_return_an_enumerator
+ enum = nil
+ assert_queries(0) do
+ enum = Post.find_in_batches(:batch_size => 1)
+ end
+ assert_queries(4) do
+ enum.first(4) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+ end
+ end
+ end
end

0 comments on commit fec1028

Please sign in to comment.