Benito Serna Tips and tools for Ruby on Rails developers

Truncate in the middle with truncate rails helper

June 19, 2023

Imagine that you want to truncate a filename, but you want to keep showing the extension of the file. Like “A big file name that…awesome.pdf”. How would you do it?

The omission parameter

With the :omission string the last characters will be replaced (defaults to “…”) for a total length not exceeding length:

string = "And they found that many people were sleeping better."
string.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"

So, you can pass as the omssion string, the last characters of your string like this:

filename = "And they found that many people were sleeping better.pdf"
filename.truncate(25, omission: "... #{filename.last(10)}")
# => "And they fo... better.pdf"

Related articles

Weekly tips and tools for Ruby on Rails developers

I send an email each week, trying to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or All post by topic.