Module: WordWrap

Defined in:
lib/miniparse/word_wrap.rb

Class Method Summary collapse

Class Method Details

.two_cols_word_wrap(*args) ⇒ Object

wrap two texts in two separate columms

Parameters:

  • separator:

    a string of characters inserted at every line between the two collums, for example ‘ ’ or ‘ | ’

Returns:

  • text with line breaks inserted as necessary



53
54
55
# File 'lib/miniparse/word_wrap.rb', line 53

def self.two_cols_word_wrap(*args)
  two_cols_word_wrap_lines(*args).join("\n")
end

.two_cols_word_wrap_lines(text_left, separator, text_right, width_left, width_right, reformat: false) ⇒ Object

same as two_cols_word_wrap(…) but returns an array of lines

Returns:

  • an array of lines containing the merged and rearranged texts



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/miniparse/word_wrap.rb', line 31

def self.two_cols_word_wrap_lines(text_left, separator, text_right, 
      width_left, width_right, reformat:false)
  left = word_wrap_lines(text_left, width_left, reformat:reformat)
  right = word_wrap_lines(text_right, width_right, reformat:reformat)

  top = [left.size, right.size].max
  lines = []
  i = 0
  while i < top
    l_part = left[i] || ''
    r_part = right[i] || ''
    lines << "%-*s%s%s" % [width_left, l_part, separator, r_part] 
    i += 1
  end
  lines
end

.word_wrap(text, width, reformat: false) ⇒ Object

wrap a text at word boundaries

Parameters:

  • text:

    the text to wrap

  • width:

    the maximum width allowed for on line before inserting line breaks

  • reformat: (defaults to: false)

    if true then the previous line breaks are removed and then the text wrappeed

Returns:

  • text with line breaks inserted as necessasry



11
12
13
14
15
16
17
# File 'lib/miniparse/word_wrap.rb', line 11

def self.word_wrap(text, width, reformat:false)
  text = text.gsub(/\s*\n/, ' ') if reformat
  
  clean = (text[-1] != "\n")
  res = text.gsub(/(.{1,#{width-1}}\S)(\s+|$)/, "\\1\n")
  (clean)? res.chomp : res 
end

.word_wrap_lines(*args) ⇒ Object

same as word_wrap(…) but returns an array of lines

Returns:

  • an array of lines containing the rearranged text



23
24
25
# File 'lib/miniparse/word_wrap.rb', line 23

def self.word_wrap_lines(*args)
  word_wrap(*args).split("\n")
end