Skip to content

Instantly share code, notes, and snippets.

@sebyx07
Created April 21, 2020 13:45
Show Gist options
  • Save sebyx07/3689d5458ede87b848403b81e3964f36 to your computer and use it in GitHub Desktop.
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
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