Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string in Rails: "..." showing up on strings at length

I'm currently trying to truncate any strings greater than 65 characters.

My code is

<title><%= truncate(title.html_safe, length:65) %></title>

It works great for titles longer than 65 characters. But titles that are exactly 65 character still get truncated.

For example:

title:"This post is exactly 65 characters characters characters characte"

shows on page as "This post is exactly 65 characters characters characters chara..."

Should I not be using truncate?

like image 940
AllieCat Avatar asked Jun 24 '14 14:06

AllieCat


2 Answers

truncate is the right method. This might be a bug in your version of rails? Here's what I get on my console:

[5] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 65)
=> "This post is exactly 56 characters characters characters characte"
[6] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 64)
=> "This post is exactly 56 characters characters characters char..."

I'm running Rails 4.0.4 in this example.

like image 97
pdobb Avatar answered Nov 14 '22 22:11

pdobb


If you are using rails 4.2 or above then you can use truncate_words method.

<title><%= (title.html_safe).truncate_words(5) %></title>
like image 32
Nimish Avatar answered Nov 14 '22 22:11

Nimish