From e292ce8a4f4559aed6faef58e03ced649513cf2f Mon Sep 17 00:00:00 2001 From: Benjamin Quorning Date: Fri, 24 Jun 2016 09:50:41 +0200 Subject: Add ActiveRecord::Result#first When you only need the first element of a result set, you shouldn't need to instantiate all of hash_rows. --- activerecord/lib/active_record/result.rb | 5 +++++ activerecord/test/cases/result_test.rb | 5 +++++ 2 files changed, 10 insertions(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 8e6cd6c82f..f45f664efe 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -75,6 +75,11 @@ module ActiveRecord hash_rows[idx] end + def first + return nil if @rows.empty? + Hash[@columns.zip(@rows.first)] + end + def last hash_rows.last end diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb index dec01dfa76..565593c500 100644 --- a/activerecord/test/cases/result_test.rb +++ b/activerecord/test/cases/result_test.rb @@ -22,6 +22,11 @@ module ActiveRecord ], result.to_hash end + 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) + end + test "each with block returns row hashes" do result.each do |row| assert_equal ['col_1', 'col_2'], row.keys -- cgit v1.2.3