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

.format_table(items, item_width, items_per_line, num_lines) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/droxi/text.rb', line 46

def self.format_table(items, item_width, items_per_line, num_lines)
  num_lines.times.map do |i|
    items[i * items_per_line, items_per_line].map do |item|
      item.ljust(item_width)
    end.join
  end
end

.get_columnsObject



36
37
38
39
40
41
42
43
44
# File 'lib/droxi/text.rb', line 36

def self.get_columns
  require 'readline'
  begin
    columns = Readline.get_screen_size[1]
    columns > 0 ? columns : DEFAULT_WIDTH
  rescue NotImplementedError
    DEFAULT_WIDTH
  end
end

.get_wrap_segment(text, columns) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/droxi/text.rb', line 54

def self.get_wrap_segment(text, columns)
  segment, sep, text = text.partition(' ')
  while !text.empty? && segment.length < columns
    head, sep, text = text.partition(' ')
    segment << " #{head}"
  end
  if segment.length > columns && segment.include?(' ')
    segment.rpartition(' ')[0]
  else
    segment
  end
end

.table(items) ⇒ Object

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



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/droxi/text.rb', line 9

def self.table(items)
  if items.empty?
    []
  else
    columns = get_columns
    item_width = items.map { |item| item.length }.max + 2
    items_per_line = [1, columns / item_width].max
    num_lines = (items.length.to_f / items_per_line).ceil
    format_table(items, item_width, items_per_line, num_lines)
  end
end

.wrap(text) ⇒ Object

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



23
24
25
26
27
28
29
30
31
32
# File 'lib/droxi/text.rb', line 23

def self.wrap(text)
  columns = get_columns
  position = 0
  lines = []
  while position < text.length
    lines << get_wrap_segment(text[position, text.length], columns)
    position += lines.last.length + 1
  end
  lines
end