1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

More Enumerable first and last for ActiveRecord::Result

`Result#first` was added at #25507. As I said at https://github.com/rails/rails/pull/25507#issuecomment-228446339,
I still prefer less code, `Result#first` is used only in `select_one`,
and `select_one` is not used in the codebase, i.e. `Result#first` and
`Result#last` are not used in the codebase. I'd not prefer to have
dedicated code for such like rarely used (almost unused) feature.

Instead of having limited `Result#first` (doesn't allow number), I'd
prefer to just use `Enumerable#first`.
This commit is contained in:
Ryuta Kamizono 2020-06-08 12:58:36 +09:00
parent 2ad2425fd3
commit 99b18b60c6
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