Method: ApplicationHelper#split_words_max_length

Defined in:
app/helpers/application_helper.rb

#split_words_max_length(text, max_length) ⇒ Array<String>

Split a string after a specified number of characters, only breaking at word boundaries.

Parameters:

  • text (String)

    The text to split.

  • max_length (Integer)

    The maximum number of characters to leave in the resulting strings.

Returns:

  • (Array<String>)


218
219
220
221
222
223
224
225
226
227
228
229
# File 'app/helpers/application_helper.rb', line 218

def split_words_max_length(text, max_length)
  words = text.split
  splat = [[]]
  words.each do |word|
    # Unless the current last element has enough space to take the extra word, create a new one.
    unless splat[-1].map { |w| w.length + 1 }.sum - 1 <= max_length - word.length
      splat << []
    end
    splat[-1] << word
  end
  splat.map { |s| s.join(' ') }
end