Truncate portions of a string to limit the whole string's length in Ruby
- by Horace Loeb
Suppose you want to generate dynamic page titles that look like this:
"It was all a dream, I used to read word up magazine" from "Juicy" by The Notorious B.I.G
I.e., "LYRICS" from "SONG_NAME" by ARTIST
However, your title can only be 69 characters total and this template will sometimes generate titles that are longer.
One strategy for solving this problem is to truncate the entire string to 69 characters. However, a better approach is to truncate the less important parts of the string first. I.e., your algorithm might look something like this:
Truncate the lyrics until the entire string is <= 69 characters
If you still need to truncate, truncate the artist name until the entire string is <= 69 characters
If you still need to truncate, truncate the song name until the entire string is <= 69 characters
If all else fails, truncate the entire string to 69 characters
Ideally the algorithm would also limit the amount each part of the string could be truncated. E.g., step 1 would really be "Truncate the lyrics to a minimum of 10 characters until the entire string is <= 69 characters"
Since this is such a common situation, I was wondering if someone has a library or code snippet that can take care of it.