Module: UI::TextHelpers

Defined in:
library/general/src/lib/ui/text_helpers.rb

Overview

Provides a set of methods to manipulate and transform UI text

Instance Method Summary collapse

Instance Method Details

#wrap_text(text, wrap = 76, separator: " ", prepend_text: "", n_lines: nil, cut_text: nil) ⇒ String

Wrap given text breaking lines longer than given wrap size. It supports custom separator, max number of lines to split in and cut text to add as last line if cut was needed.

Parameters:

  • text (String)

    to be wrapped

  • wrap (String) (defaults to: 76)

    size

  • optional (Hash <String>)

    parameters as separator and prepend_text.

Returns:

  • (String)

    wrap text



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'library/general/src/lib/ui/text_helpers.rb', line 33

def wrap_text(text, wrap = 76, separator: " ", prepend_text: "",
  n_lines: nil, cut_text: nil)
  lines = []
  message_line = prepend_text
  text.split(/\s+/).each_with_index do |t, i|
    if !message_line.empty? && "#{message_line}#{t}".size > wrap
      lines << message_line
      message_line = ""
    end

    message_line << separator if !message_line.empty? && i != 0
    message_line << t
  end

  lines << message_line if !message_line.empty?

  if n_lines && lines.size > n_lines
    lines = lines[0..n_lines - 1]
    lines << cut_text if cut_text
  end

  lines.join("\n")
end