Truncating a String within a View – Ruby on Rails

Another quick post, just on how to truncate a string within a view. I used the following in order to ensure that my order_item title is never longer than 100 characters:

Title: <%= truncate(order_item.title, :length => 100, :seperator => ' ...') %><br />


This will output the title, if it’s longer than 100 characters the string will be shortened to 100 characters (minus the separator’s length). The neat thing about truncate is all the separator functionality is built in – you don’t have to throw any if/else logic in to check whether it’s required or not.


#Less than 100 characters
Title: lentesque porttitor

#More than 100 characters
Title: lentesque porttitor, velit vel ullamcorper pharetra, augue erat pharetra risus, quis bibendum fel…

Good Luck!

Leave a Reply