Skip to content

Instantly share code, notes, and snippets.

@xtian
Created January 3, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xtian/8242820 to your computer and use it in GitHub Desktop.
Save xtian/8242820 to your computer and use it in GitHub Desktop.
multiline_truncate
def multiline_truncate(string, width, max_lines)
lines = word_wrap(string, line_width: width).split("\n")
# string does not wrap past maximum number of lines
return string unless lines[max_lines].present?
# join the last two lines and truncate them
last_line = "#{lines[max_lines - 1]} #{lines[max_lines]}"
lines[max_lines - 1] = truncate(last_line, length: width)
# return lines separated by break tags
lines.take(max_lines).join('<br>').html_safe
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment