Skip to content

Instantly share code, notes, and snippets.

@trans
Created June 5, 2010 16:26
Show Gist options
  • Save trans/426742 to your computer and use it in GitHub Desktop.
Save trans/426742 to your computer and use it in GitHub Desktop.
class String
# Returns short abstract of long strings; not exceeding +range+
# characters. If range is an integer then the minimum is 20%
# of the maximum. The string is chopped at the nearest word
# if possible, and appended by +ellipsis+, which defaults
# to '...'.
#
# CREDIT: George Moschovitis, Trans
def brief(range=76, ellipsis="...")
if Range===range
min = range.first
max = range.last
else
max = range
min = max - (max/5).to_i
range = min..max
end
if size > max
cut_at = rindex(/\b/, max) || max
cut_at = max if cut_at < min
xstring = slice(0, cut_at)
xstring.chomp(" ") + ellipsis
else
self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment