Module: Defcli::Formatting

Defined in:
lib/defcli/formatting.rb

Class Method Summary collapse

Class Method Details

.fit(txt, width = 79) ⇒ Array

Fit a text in a given width (number of chars).

Parameters:

  • txt (String)
  • width (Integer) (defaults to: 79)

    maximum width

Returns:

  • (Array)

    list of lines of text



10
11
12
13
14
15
16
# File 'lib/defcli/formatting.rb', line 10

def fit(txt, width = 79)
  return [] if width < 1

  # from https://stackoverflow.com/a/7567210/735926
  r = /(.{1,#{width}})(?:\s|$)/m
  txt.split("\n").map { |l| l.scan(r) }.flatten
end

.format_result(r, color = true) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/defcli/formatting.rb', line 42

def format_result(r, color = true)
  require "colored" if color

  word = r[:word]
  word = word.bold if color

  rating = format_result_rating(r, color)

  definition = tab(fit(r[:definition], 75)).join "\n"

  text = "* #{word}"
  text << " (#{rating})" if rating
  text << ":\n\n#{definition}\n"

  text << "(๐Ÿ“ #{r[:location]})\n" if r[:location]

  text << (format_result_examples(r, color) or "")

  text + "\n\n"
end

.format_results(results, color = true) ⇒ String

Format results for text output (e.g. in the terminal)

Parameters:

  • results (Array<Hash>)

    array of results

  • color (Boolean) (defaults to: true)

    colored output

Returns:

  • (String)


38
39
40
# File 'lib/defcli/formatting.rb', line 38

def format_results(results, color = true)
  results.map { |r| format_result(r, color) }.join "\n"
end

.tab(txt, width = 4) ⇒ String

Add a tab at the beginning of a text. If itโ€™s a list, add a tab at the beginning of each element.

Parameters:

  • txt (String)

    The text to tab, may be a string or a list of strings

  • width (Integer) (defaults to: 4)

    tab width

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
# File 'lib/defcli/formatting.rb', line 24

def tab(txt, width = 4)
  return txt if width <= 0

  tab = " " * width

  return tab + txt if txt.is_a? String

  txt.map { |l| tab + l }
end