Module: Text

Defined in:
lib/droxi/text.rb

Overview

Module containing text-manipulation methods.

Constant Summary collapse

DEFAULT_WIDTH =

The assumed width of the terminal if GNU Readline can’t retrieve it.

72

Class Method Summary collapse

Class Method Details

.table(items) ⇒ Object

Format an Array of Strings as a table and return an Array of lines in the result.



8
9
10
11
12
13
14
# File 'lib/droxi/text.rb', line 8

def self.table(items)
  return [] if items.empty?
  width = terminal_width
  item_width = items.map { |item| item.size }.max + 2
  items_per_line = [1, width / item_width].max
  format_table(items, item_width, items_per_line)
end

.tokenize(string, include_empty: false) ⇒ Object

Split a String into tokens, allowing for backslash-escaped spaces, and return the resulting Array.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/droxi/text.rb', line 30

def self.tokenize(string, include_empty: false)
  tokens = string.split
  tokens << '' if include_empty && (string.empty? || string.end_with?(' '))
  tokens.reduce([]) do |list, token|
    list << if !list.empty? && list.last.end_with?('\\')
              "#{list.pop.chop} #{token}"
            else
              token
            end
  end
end

.wrap(text) ⇒ Object

Wrap a String to fit the terminal and return an Array of lines in the result.



18
19
20
21
22
23
24
25
26
# File 'lib/droxi/text.rb', line 18

def self.wrap(text)
  width, position = terminal_width, 0
  lines = []
  while position < text.size
    lines << get_wrap_segment(text[position, text.size], width)
    position += lines.last.size + 1
  end
  lines
end