Skip to content

Commit 609bc40

Browse files
committed
Merge pull request rails#12653 from releu/short_arrays_in_inspect
Short arrays in record.inspect
2 parents a5e2800 + 510601c commit 609bc40

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* ActiveRecord::Base#attribute_for_inspect now truncates long arrays (more than 10 elements)
2+
3+
*Jan Bernacki*
4+
15
* Allow for the name of the schema_migrations table to be configured.
26

37
*Jerad Phelps*

activerecord/lib/active_record/attribute_methods.rb

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -245,9 +245,10 @@ def attributes
245245

246246
# Returns an <tt>#inspect</tt>-like string for the value of the
247247
# attribute +attr_name+. String attributes are truncated upto 50
248-
# characters, and Date and Time attributes are returned in the
249-
# <tt>:db</tt> format. Other attributes return the value of
250-
# <tt>#inspect</tt> without modification.
248+
# characters, Date and Time attributes are returned in the
249+
# <tt>:db</tt> format, Array attributes are truncated upto 10 values.
250+
# Other attributes return the value of <tt>#inspect</tt> without
251+
# modification.
251252
#
252253
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
253254
#
@@ -256,13 +257,19 @@ def attributes
256257
#
257258
# person.attribute_for_inspect(:created_at)
258259
# # => "\"2012-10-22 00:15:07\""
260+
#
261+
# person.attribute_for_inspect(:tag_ids)
262+
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
259263
def attribute_for_inspect(attr_name)
260264
value = read_attribute(attr_name)
261265

262266
if value.is_a?(String) && value.length > 50
263267
"#{value[0, 50]}...".inspect
264268
elsif value.is_a?(Date) || value.is_a?(Time)
265269
%("#{value.to_s(:db)}")
270+
elsif value.is_a?(Array) && value.size > 10
271+
inspected = value.first(10).inspect
272+
%(#{inspected[0...-1]}, ...])
266273
else
267274
value.inspect
268275
end

activerecord/test/cases/adapters/postgresql/array_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,11 @@ def test_insert_fixture
113113
assert_equal(PgArray.last.tags, tag_values)
114114
end
115115

116+
def test_attribute_for_inspect_for_array_field
117+
record = PgArray.new { |a| a.ratings = (1..11).to_a }
118+
assert_equal("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]", record.attribute_for_inspect(:ratings))
119+
end
120+
116121
private
117122
def assert_cycle field, array
118123
# test creation

0 commit comments

Comments
 (0)