Module: UD::Formatting

Defined in:
lib/ud/formatting.rb

Overview

Formatting tools for query‘s output

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



13
14
15
16
17
18
19
# File 'lib/ud/formatting.rb', line 13

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

  # from http://stackoverflow.com/a/7567210/735926
  r = /(.{1,#{width}})(?:\s|$)/m
  txt.split("\n").map { |l| l.scan(r) }.flatten
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)


26
27
28
29
30
31
32
33
34
# File 'lib/ud/formatting.rb', line 26

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

  tab = ' ' * width

  return tab + txt if txt.is_a?(String)

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

.text(results, color = true) ⇒ String

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

Parameters:

  • results (Array<Hash>)

    this must be an array of results, as returned by UD.query.

  • color (Boolean) (defaults to: true)

    colored output

Returns:

  • (String)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ud/formatting.rb', line 41

def text(results, color=true)
  require 'colored' if color

  results.map do |r|

    word  = r[:word]
    upvotes = r[:upvotes]
    downvotes = r[:downvotes]

    if (color)
      word      = word.bold
      upvotes   = upvotes.to_s.green
      downvotes = downvotes.to_s.red
    end

    votes = "#{upvotes}/#{downvotes}"
    definition = tab(fit(r[:definition], 75)).join("\n")
    example    = tab(fit(r[:example], 75)).join("\n")

    <<-EOD
* #{word} (#{votes}):

#{definition}

 Example:
#{example}


    EOD

  end.join("\n")
end