提交 99b18b60 编写于 作者: R Ryuta Kamizono

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`.
上级 2ad2425f
......@@ -92,18 +92,9 @@ def [](idx)
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 @@ def result
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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册