Skip to content

Instantly share code, notes, and snippets.

@netguru
Created September 13, 2010 14:01
Show Gist options
  • Save netguru/577326 to your computer and use it in GitHub Desktop.
Save netguru/577326 to your computer and use it in GitHub Desktop.
class String
def truncate_full_words limit = 64, completion = "..."
self.length > limit ? "#{self[0..(self.rindex(' ', limit) || limit)-1]}#{competion}" : self
end
def truncate_full_words! limit = 64, completion = "..."
self.replace(self.truncate_full_words limit, completion)
end
end
>> some_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec enim nibh."
=> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec enim nibh."
>> some_string.truncate_full_words
=> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment