Skip to content

Instantly share code, notes, and snippets.

@sebyx07
Created May 31, 2020 14:52
Show Gist options
  • Save sebyx07/3f61db368d302d9b28cb5596a84f7d64 to your computer and use it in GitHub Desktop.
Save sebyx07/3f61db368d302d9b28cb5596a84f7d64 to your computer and use it in GitHub Desktop.
rails truncate text, smart way
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