Module: Clive::Output

Extended by:
Output
Included in:
Output
Defined in:
lib/clive/output.rb

Constant Summary collapse

TERMINAL_WIDTH =

If the terminal width can’t be determined use a sensible default value

80

Instance Method Summary collapse

Instance Method Details

#pad(str, len, with = " ") ⇒ Object

Parameters:

  • str (String)

    String to pad.

  • len (Integer)

    Length to pad string to.

  • with (String) (defaults to: " ")

    String to add to str.



10
11
12
13
14
# File 'lib/clive/output.rb', line 10

def pad(str, len, with=" ")
  diff = len - str.clear_colours.size
  str += with * diff unless diff < 0
  str
end

#terminal_widthInteger?

Returns Width of terminal window, or nil if it cannot be determined.

Returns:

  • (Integer, nil)

    Width of terminal window, or nil if it cannot be determined.

See Also:



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/clive/output.rb', line 63

def terminal_width
  if (ENV['COLUMNS'] =~ /^\d+$/)
    ENV['COLUMNS'].to_i
  elsif (RUBY_PLATFORM =~ /java/ || (!STDIN.tty? && ENV['TERM'])) && command_exists?('tput')
    `tput cols`.to_i
  elsif STDIN.tty? && command_exists?('stty')
    # returns 'height width'
    `stty size`.scan(/\d+/).last.to_i
  else
    TERMINAL_WIDTH
  end
rescue
  TERMINAL_WIDTH
end

#wrap_text(str, left_margin, width) ⇒ Object

Wraps text. Each line is split by word and then a newline is inserted when the words exceed the allowed width. Lines after the first will have left_margin spaces inserted.

Examples:


Clive::Output.wrap_text("Lorem ipsum dolor sit amet, consectetur 
adipisicing elit, sed do eiusmod tempor incididunt ut labore et 
dolore magna aliqua.", 4, 24)
#=> "Lorem ipsum dolor
#    sit amet,
#    consectetur
#    adipisicing elit,
#    sed do eiusmod
#    tempor incididunt ut
#    labore et dolore
#    magna aliqua."

Parameters:

  • str (String)

    Text to be wrapped

  • left_margin (Integer)

    Width of space at left

  • width (Integer)

    Total width of text, ie. from the left of the screen



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/clive/output.rb', line 38

def wrap_text(str, left_margin, width)
  text_width = width - left_margin
  
  words = str.split(" ")
  r = [""]
  i = 0
  
  words.each do |word|
    if (r[i] + word).clear_colours.size < text_width
      r[i] << " " << word
    else
      i += 1
      r[i] = word
    end
  end
  
  # Clean up strings
  r.map! {|i| i.strip }
  
  ([r[0]] + r[1..-1].map {|i| l_pad(i, left_margin) }).join("\n")
end