From 7d0053e6a716be6345daa5e49dceda27ba8dfdb6 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Fri, 6 Jul 2012 16:53:33 +0200 Subject: Limit the number of records in Relation#inspect While it's interesting to have the results array, it can make a console or a webpage freeze if there are a lot of them. So this limits the number of records displayed in #inspect to 10 and tells how much were effectively found. --- activerecord/CHANGELOG.md | 6 ++++-- activerecord/lib/active_record/relation.rb | 14 +++++++++++++- activerecord/test/cases/relations_test.rb | 5 +++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index ccaa2ad8f1..95967c61ee 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -24,12 +24,14 @@ dealing with a `Relation` object rather than an array:. User.where(:age => 30).inspect - # => , #]> + # => , #] ...> User.where(:age => 30).to_a.inspect # => [#, #] - *Brian Cardarella & Jon Leighton* + The number of records displayed will be limited to 10. + + *Brian Cardarella, Jon Leighton & Damien Mathieu* * Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later. Example: diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 7725331694..dc00448dff 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -515,7 +515,19 @@ module ActiveRecord end def inspect - "#<#{self.class.name} #{to_a.inspect}>" + text = if limit_value && limit_value <= 10 + to_a.inspect + else + entries = limit(11).to_a + if entries.size > 10 + entries.pop + "[#{entries.map(&:inspect).join(', ')}, ...]" + else + entries.inspect + end + end + + "#<#{self.class.name} #{text}>" end private diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 7fdd42f150..bdf14e0a85 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1316,4 +1316,9 @@ class RelationTest < ActiveRecord::TestCase relation = Post.limit(2) assert_equal "#", relation.inspect end + + test "relations limits the records in #inspect at 10" do + relation = Post.limit(11) + assert_equal "#", relation.inspect + end end -- cgit v1.2.3