module ActionView::Helpers::TextHelper
def word_wrap(text, line_width: 80, break_sequence: "\n")
word_wrap('Once upon a time', line_width: 1, break_sequence: "\r\n")
You can also specify a custom +break_sequence+ ("\n" by default)
# => Once\nupon\na\ntime
word_wrap('Once upon a time', line_width: 1)
# => Once\nupon a\ntime
word_wrap('Once upon a time', line_width: 8)
# => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
# => Once upon a time
word_wrap('Once upon a time')
(which is 80 by default).
breaks on the first whitespace character that does not exceed +line_width+
Wraps the +text+ into lines no longer than +line_width+ width. This method
def word_wrap(text, line_width: 80, break_sequence: "\n") text.split("\n").collect! do |line| line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").rstrip : line end * break_sequence end