Module: ReqWrap::Generator::StringWrapper

Defined in:
lib/req_wrap/generator/string_wrapper.rb

Class Method Summary collapse

Class Method Details

.wrap_string(str, to:) ⇒ Object



6
7
8
# File 'lib/req_wrap/generator/string_wrapper.rb', line 6

def self.wrap_string(str, to:)
  wrap_words(str.split(' '), [], to).map { |words| words.join(' ') }
end

.wrap_words(words, result, to) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/req_wrap/generator/string_wrapper.rb', line 10

def self.wrap_words(words, result, to)
  # Partitioning is finished if there is nothing more to
  # partition;
  #
  return result if words.empty?

  current_size = 0
  line, rest = words.partition do |word|
    current_size += word.size + 1
    current_size - 1 <= to
  end

  # Use the next word if wrapping cannot be performed;
  #
  # This means that the word length is larger than the 'to'
  # argument
  #
  line << rest.shift if line.empty?

  result << line

  # Continue partitioning the rest of words
  #
  wrap_words(rest, result, to)
end