Created
March 4, 2009 21:45
-
-
Save rgo/74026 to your computer and use it in GitHub Desktop.
Awesome truncate
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
# 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