8

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?

Jacob
  • 2,212
  • 1
  • 12
  • 18
AllieCat
  • 3,890
  • 10
  • 31
  • 45

5 Answers5

7

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.

pdobb
  • 17,688
  • 5
  • 59
  • 74
5

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

<title><%= (title.html_safe).truncate_words(5) %></title>
jain77
  • 173
  • 1
  • 7
Nimish
  • 1,053
  • 13
  • 29
2

title = "This post is exactly 56 characters characters characters characte".length => 65

<title><%= truncate(title.html_safe, length:56) %></title> # will be truncated

<title><%= truncate(title.html_safe, length:65) %></title> # this should work fine, I just tried.

Rails 3.2.17

Nithin
  • 3,679
  • 3
  • 30
  • 55
1

the truncate method work just as expected. Please output the length after your invocation of title.html_safe, is it possible that your string contains some trailing spaces?

nickcen
  • 1,682
  • 10
  • 10
1

We call it Ellipsis. Just to add to the above answers you can achieve ellipsis by css, jquery and rails.

css:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Jquery:

There is a really good jquery plugin dotdotdot. I have used it one of my projects and it works like a charm. It uses height and width of your parent element smartly to show ellipsis.

Rails:

Rails has a text helper truncate which can be used like:

<%= truncate("Once upon a time in a world far far away", length: 65) %>

CSS is obviously the quickest way to achieve ellipsis but it has its disadvantages that it doesn't provide a way to limit your characters and it's tricky to get it to work for multiple lines.

Jquery plugin dotdotdot works great for multiple lines but i don't think it has option to specify character limit either.

Rails truncate it obviously server side and will allow you an option to specify character limit.

Mandeep
  • 9,093
  • 2
  • 26
  • 36