mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #39568 from kamipo/more_enumerable_first
More Enumerable `first` and `last` for `ActiveRecord::Result`
This commit is contained in:
commit
b4bf143d6a
2 changed files with 26 additions and 11 deletions
|
@ -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:
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue