Permalink
Browse files

`find_in_batches` now returns an `Enumerator` when called without a b…

…lock, so that it

can be chained with other `Enumerable` methods.
  • Loading branch information...
marcandre committed Dec 5, 2013
1 parent 5086c8c commit 0aad463cfbe9853fd3a7ab0f8e4e0a34715fd62c
@@ -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*
+
* Polymorphic belongs_to associations with the `touch: true` option set update the timestamps of
the old and new owner correctly when moved between owners of different types.
@@ -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
+ #
# ==== Options
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
@@ -86,6 +94,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
@@ -170,4 +170,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 0aad463

Please sign in to comment.