Permalink
Browse files

Change Result#each to return an Enumerator when called without a block.

As with #10992, this lets us call #with_index, etc on the results.
  • Loading branch information...
Empact committed Jun 18, 2013
1 parent 353a398 commit d6cfbaea72e1b2852ed3206c0ffea8a572048369
Showing with 43 additions and 1 deletion.
  1. +5 −0 activerecord/CHANGELOG.md
  2. +5 −1 activerecord/lib/active_record/result.rb
  3. +33 −0 activerecord/test/cases/result_test.rb
@@ -1,3 +1,8 @@
+* `ActiveRecord::Result.each` now returns an `Enumerator` when called without
+ a block, so that it can be chained with other `Enumerable` methods.
+
+ *Ben Woosley*
+
* Fixture setup does no longer depend on `ActiveRecord::Base.configurations`.
This is relevant when `ENV["DATABASE_URL"]` is used in place of a `database.yml`.
@@ -18,7 +18,11 @@ def initialize(columns, rows, column_types = {})
end
def each
- hash_rows.each { |row| yield row }
+ if block_given?
+ hash_rows.each { |row| yield row }
+ else
+ hash_rows.to_enum
+ end
end
def to_hash
@@ -0,0 +1,33 @@
+require "cases/helper"
+
+module ActiveRecord
+ class ResultTest < ActiveRecord::TestCase
+
+ def result
+ Result.new(['col_1', 'col_2'], [
+ ['row 1 col 1', 'row 1 col 2'],
+ ['row 2 col 1', 'row 2 col 2']
+ ])
+ end
+
+ def test_to_hash_returns_row_hashes
+ assert_equal [
+ {'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'},
+ {'col_1' => 'row 2 col 1', 'col_2' => 'row 2 col 2'}
+ ], result.to_hash
+ end
+
+ def test_each_with_block_returns_row_hashes
+ result.each do |row|
+ assert_equal ['col_1', 'col_2'], row.keys
+ end
+ end
+
+ def test_each_without_block_returns_an_enumerator
+ result.each.with_index do |row, index|
+ assert_equal ['col_1', 'col_2'], row.keys
+ assert_kind_of Integer, index
+ end
+ end
+ end
+end

0 comments on commit d6cfbae

Please sign in to comment.