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:  100, :seperator => ' ...') %>

 

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.

Output:

#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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s