Optimize ActiveRecord::Result#last

If you only want the last element of a result set, there's no need to create all
of hash_rows. Also, add a test.
This commit is contained in:
Benjamin Quorning 2016-06-24 09:49:42 +02:00
parent af834fb2c0
commit 763de2ac1c
2 changed files with 7 additions and 1 deletions

@ -81,7 +81,8 @@ def first
end
def last
hash_rows.last
return nil if @rows.empty?
Hash[@columns.zip(@rows.last)]
end
def cast_values(type_overrides = {}) # :nodoc:

@ -27,6 +27,11 @@ def result
{'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'}, result.first)
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)
end
test "each with block returns row hashes" do
result.each do |row|
assert_equal ['col_1', 'col_2'], row.keys