Skip to content

Instantly share code, notes, and snippets.

@rgo
Created March 4, 2009 21:45
Show Gist options
  • Save rgo/74026 to your computer and use it in GitHub Desktop.
Save rgo/74026 to your computer and use it in GitHub Desktop.
Awesome truncate
# Awesome truncate
# From: http://daniel.collectiveidea.com/blog/2007/7/10/a-prettier-truncate-helper
#
# First regex truncates to the length, plus the rest of that word, if any.
# Second regex removes any trailing whitespace or punctuation (except ;).
# Unlike the regular truncate method, this avoids the problem with cutting
# in the middle of an entity ex.: truncate("this & that",9) => "this &am..."
# though it will not be the exact length.
def awesome_truncate(text, length = 30, truncate_string = "...")
return if text.nil?
l = length - truncate_string.chars.length
text.chars.length > length ? text[/\A.{#{l}}\w*\;?/m][/.*[\w\;]/m] + truncate_string : text
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment