Reputation: 81641
I'm inspecting an ActiveRecord object in pry and the Rails console, but one of the attributes is really verbose.
my_record.document.to_s.length # => 45480
How can I view the record, telling Rails that I only want a few dozen characters from my_record.document
before truncating it with an ellipsis?
Upvotes: 1
Views: 531
Reputation: 11245
You can use the truncate
method from action view to do this. For instance, if you wanted to truncate to 300 characters, including the ellipsis, then you could do the following.
truncate(my_record.document.to_s, length: 300)
You'll first have to include ActionView::Helper methods in order to have truncate
available in your console.
include ActionView::Helpers
This is also trivial to do in pure Ruby if you want to go that route:
max_length = 10
"This could be a really long string".first(max_length - 3).ljust(max_length, "...")
outputs:
"This co..."
EDIT
If you want to truncate inspection for a single attribute override the attribute_for_inspect
:
For instance, you could truncate display of the document
column to 300 characters (including ellipsis) as follows:
In your model:
def attribute_for_inspect(attr_name)
if attr_name.to_sym == :document
max_length = 300
value = read_attribute(attr_name).to_s
# You should guard against nil here.
value.first(max_length - 3).ljust(max_length, "...")
else
super
end
end
attr_for_inspect
is defined in ActiveRecord::AttributeMethods
if you want to see how it works: https://github.com/rails/rails/blob/52ce6ece8c8f74064bb64e0a0b1ddd83092718e1/activerecord/lib/active_record/attribute_methods.rb#L296.
Upvotes: 2