Created
January 3, 2014 17:55
-
-
Save xtian/8242820 to your computer and use it in GitHub Desktop.
multiline_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
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