aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/batches_test.rb
diff options
context:
space:
mode:
authorCaius Durling <dev@caius.name>2011-05-31 22:48:40 +0100
committerCaius Durling <dev@caius.name>2011-06-21 19:55:21 +0100
commit96be08de257460cfd66d7f946be95e07160cea6f (patch)
treef65fa6ff7db628bb34f67cfd07bf26739ad188d5 /activerecord/test/cases/batches_test.rb
parent62570e8626c67f9d38b28246304b938aab9d9fbe (diff)
downloadrails-96be08de257460cfd66d7f946be95e07160cea6f.tar.gz
rails-96be08de257460cfd66d7f946be95e07160cea6f.tar.bz2
rails-96be08de257460cfd66d7f946be95e07160cea6f.zip
Stop find_in_batches using the records after yielding.
Currently if the code that calls .find_in_batches modifies the yielded array in place then .find_in_batches can enter an infinite loop searching with ruby object ids in the database instead of the primary key of records in the database. This happens because it naively assumes the yielded array hasn't been modified before calling #id on the last object in the array. And ruby (1.8 at least) alias' #id to #object_id so an integer is still returned no matter what the last object is. By moving finding the #id of the last object before yielding the array it means the calling code can do whatever it wants to the array in terms of modifying it in place, and .find_in_batches doesn't care.
Diffstat (limited to 'activerecord/test/cases/batches_test.rb')
-rw-r--r--activerecord/test/cases/batches_test.rb16
1 files changed, 16 insertions, 0 deletions
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index 31e00c998c..102b8d69da 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -93,4 +93,20 @@ class EachTest < ActiveRecord::TestCase
end
end
end
+
+ def test_find_in_batches_should_not_use_records_after_yielding_them_in_case_original_array_is_modified
+ not_a_post = "not a post"
+ not_a_post.stubs(:id).raises(StandardError, "not_a_post had #id called on it")
+
+ assert_nothing_raised do
+ Post.find_in_batches(:batch_size => 1) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+
+ batch.map! { not_a_post }
+ end
+ end
+
+ end
+
end