I am surprised that none of the answers is really correct (or limited by using rails helper) although this is very old question, so here is the solution.
Lets clearly formulate what it the goal first. We want truncate string s
to 30 characters and cut the last word out as well if it can not entirely fit in. We also want to truncate trailing spaces from the result and add ellipsis, if the text was shortened.
If the text is longer then limit, than the shortening is as easy as
s[0,s.rindex(/\s/,30)].rstrip + '...'
If we wanted the entire result to be max 30 characters, than it is as simple as subtracting the length of ellipse from 30. So because we use three dots (and not one three-dot character) than we need
s[0,s.rindex(/\s/,27)].rstrip + '...'
And the final result (with the test whether we need to truncate at all) is:
if s.length<=30
s
else
s[0,s.rindex(/\s/,27)].rstrip + '...'
end
Thats it.
Note: There are some shady cases, when the desired result is not obvious. Here they are:
- If the string ends with lots of spaces (
s= "Helo word "
) but is shorter than 30. Should the spaces be preserved? - Currently they are.
- The same as above, but the spaces at the end cross the limit o 30. Like in (
s= "Twentyseven chars long text "
) - Currently all spaces ad the end are truncated and ellipsis added.