The Spaghetti Refactory Established 2015

Get easy snippets in Rails views with `truncate`

Silly me, when I had a Note model that I wanted to show just a snippet of the note content with a link to view the full note, I wrote three separate methods that worked in tandem to do this. Then, I found out about truncate:

truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."

truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."

The separator option will only truncate the text at that char, so in this case, it won't break up words, it will get to 17 characters, then find the previous space (or whatever character is specified as the separator) and truncate there. As you can see, without the separator option, it counts up to 14 and adds an ellipsis to make the total character count 17.

There are several other options to extend this that you can check out in the docs. NOTE: This can be used by default in Rails views because it's part of ActionView::Helpers::TextHelper, but must be specifically included if you want to use it elsewhere in the app.

So save yourself some time and trouble, don't be like me and start making up snippet methods when there's a perfectly good one already built!

Tags