Truncate a string without cut in the middle of a word in rails

Sebastien picture Sebastien · Jan 3, 2012 · Viewed 13.3k times · Source

How can i truncate a text to the closest position with rails 3 whithout cut in the middle of a word?

For exemple, I have the string :

"Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum."

If i cut it, i want to cut like this :

"Praesent commodo cursus magna, vel scelerisque nisl ..."

And not :

"Praesent commodo cursus magna, vel scelerisque nisl conse..."

Answer

Suhail Patel picture Suhail Patel · Jan 3, 2012

If you pass in a separator to the truncate method it will perform a natural word break instead of truncating at a middle of a word

Something like this should work (vary the length to whatever you want to remove it altogether if you want the default of 30 characters):

truncate("Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.", :length => 17, :separator => ' ')

More information about the options you can have in truncate can be found in the Documentation