Created
May 31, 2020 14:52
-
-
Save sebyx07/3f61db368d302d9b28cb5596a84f7d64 to your computer and use it in GitHub Desktop.
rails truncate text, smart way
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
def truncate(text, max) | |
return text if text.size < max | |
last_word_index = text[max] == " " ? -1 : -2 # check if it's ending, then we can include it | |
text[0..max - 1].split(" ")[0..last_word_index].join(" ") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment