Skip to content

Instantly share code, notes, and snippets.

@thibaudgg
Created May 19, 2010 10:09
Show Gist options
  • Save thibaudgg/406162 to your computer and use it in GitHub Desktop.
Save thibaudgg/406162 to your computer and use it in GitHub Desktop.
truncate in the middle like Finder
# If text is longer than +options[:length]+ (defaults to 30), text will be middle-truncated
# and the last characters will be replaced with the +options[:omission]+ (defaults to "...").
def truncate_middle(text, *args)
options = args.extract_options!
options.reverse_merge!(:length => 30, :omission => "...")
if text
if text.mb_chars.length <= options[:length]
text
else
tl = options[:omission].mb_chars.length
hl = (options[:length]-tl)/2
text[0..hl] + options[:omission] + text[-hl..-1]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment