Skip to content

Commit

Permalink
Return sized enumerator from Batches#find_each
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Feb 5, 2014
1 parent d37f395 commit 13d2696
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 4 deletions.
8 changes: 7 additions & 1 deletion activerecord/CHANGELOG.md
@@ -1,4 +1,10 @@
* `find_in_batches` now returns an `Enumerator` that can calculate its size.
<<<<<<< HEAD
* `find_in_batches`, `find_each` now
return an `Enumerator` that can calculate its size.
=======
* `find_in_batches`, `find_each`, `Result#each` now returns an `Enumerator`
that can calculate its size.
>>>>>>> 5863938... Return sized enumerator from Result#each
See also #13938.

Expand Down
4 changes: 3 additions & 1 deletion activerecord/lib/active_record/relation/batches.rb
Expand Up @@ -52,7 +52,9 @@ def find_each(options = {})
records.each { |record| yield record }
end
else
enum_for :find_each, options
enum_for :find_each, options do
options[:start] ? where(table[primary_key].gteq(options[:start])).size : size
end
end
end

Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/result.rb
Expand Up @@ -54,7 +54,7 @@ def each
if block_given?
hash_rows.each { |row| yield row }
else
hash_rows.to_enum
hash_rows.to_enum { @rows.size }
end
end

Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/batches_test.rb
Expand Up @@ -35,6 +35,14 @@ def test_each_should_return_an_enumerator_if_no_block_is_present
end
end

if Enumerator.method_defined? :size
def test_each_should_return_a_sized_enumerator
assert_equal 11, Post.find_each(:batch_size => 1).size
assert_equal 5, Post.find_each(:batch_size => 2, :start => 7).size
assert_equal 11, Post.find_each(:batch_size => 10_000).size
end
end

def test_each_enumerator_should_execute_one_query_per_batch
assert_queries(@total + 1) do
Post.find_each(:batch_size => 1).with_index do |post, index|
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/result_test.rb
Expand Up @@ -30,5 +30,11 @@ def test_each_without_block_returns_an_enumerator
assert_kind_of Integer, index
end
end

if Enumerator.method_defined? :size
def test_each_without_block_returns_a_sized_enumerator
assert_equal 3, result.each.size
end
end
end
end
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/core_ext/enumerable.rb
Expand Up @@ -35,7 +35,7 @@ def index_by
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
else
to_enum :index_by
to_enum(:index_by) { size }
end
end

Expand Down

0 comments on commit 13d2696

Please sign in to comment.