Created
April 21, 2020 13:45
-
-
Save sebyx07/3689d5458ede87b848403b81e3964f36 to your computer and use it in GitHub Desktop.
Smart way to truncate string strings in ruby based on number of chars. It enforces the maxium size, so you don't get validation errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module StringTruncate | |
def string_truncate(string, max_size, terminator="...") | |
size = 0 | |
words = [] | |
string.split.each do |word| | |
size += word.size | |
words << word | |
break if size >= max_size | |
size += 1 | |
end | |
return words.join(" ") if size <= max_size | |
plus_terminator_size = size + terminator.size | |
return words.push(terminator).join(" ") if plus_terminator_size <= max_size | |
while plus_terminator_size > max_size | |
last_word = words.pop | |
plus_terminator_size -= last_word.size + 1 | |
end | |
words.join(" ") + terminator | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment