Merge pull request #39568 from kamipo/more_enumerable_first

More Enumerable `first` and `last` for `ActiveRecord::Result`
This commit is contained in:
Ryuta Kamizono 2020-06-09 15:52:42 +09:00 committed by GitHub
commit b4bf143d6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 11 deletions

View File

@ -92,18 +92,9 @@ module ActiveRecord
hash_rows[idx]
end
# Returns the first record from the rows collection.
# If the rows collection is empty, returns +nil+.
def first
return nil if @rows.empty?
Hash[@columns.zip(@rows.first)]
end
# Returns the last record from the rows collection.
# If the rows collection is empty, returns +nil+.
def last
return nil if @rows.empty?
Hash[@columns.zip(@rows.last)]
def last(n = nil)
n ? hash_rows.last(n) : hash_rows.last
end
def cast_values(type_overrides = {}) # :nodoc:

View File

@ -42,11 +42,35 @@ module ActiveRecord
test "first returns first row as a hash" do
assert_equal(
{ "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, result.first)
assert_equal [
{ "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" },
], result.first(1)
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.first(2)
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" },
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
], result.first(3)
end
test "last returns last row as a hash" do
assert_equal(
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, result.last)
assert_equal [
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
], result.last(1)
assert_equal [
{ "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" },
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
], result.last(2)
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" },
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
], result.last(3)
end
test "each with block returns row hashes" do