diff options
author | Benjamin Quorning <benjamin@quorning.net> | 2016-06-24 09:49:42 +0200 |
---|---|---|
committer | Benjamin Quorning <benjamin@quorning.net> | 2016-06-24 11:43:48 +0200 |
commit | 763de2ac1c85d3e9f82639783a55244d6c0517c2 (patch) | |
tree | b3ea6e9eec0572399f4d9d4d0c36867f86290ed9 | |
parent | af834fb2c03358fe9a1b8fd9ec36eb5658a63260 (diff) | |
download | rails-763de2ac1c85d3e9f82639783a55244d6c0517c2.tar.gz rails-763de2ac1c85d3e9f82639783a55244d6c0517c2.tar.bz2 rails-763de2ac1c85d3e9f82639783a55244d6c0517c2.zip |
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.
-rw-r--r-- | activerecord/lib/active_record/result.rb | 3 | ||||
-rw-r--r-- | activerecord/test/cases/result_test.rb | 5 |
2 files changed, 7 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index f45f664efe..b9fd0f5326 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -81,7 +81,8 @@ module ActiveRecord end def last - hash_rows.last + return nil if @rows.empty? + Hash[@columns.zip(@rows.last)] end def cast_values(type_overrides = {}) # :nodoc: diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb index 565593c500..83dc5347e0 100644 --- a/activerecord/test/cases/result_test.rb +++ b/activerecord/test/cases/result_test.rb @@ -27,6 +27,11 @@ module ActiveRecord {'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 |