Module: Clive::Output
Constant Summary collapse
- TERMINAL_WIDTH =
If the terminal width can’t be determined use a sensible default value
80
Instance Method Summary collapse
- #pad(str, len, with = " ") ⇒ Object
-
#terminal_width ⇒ Integer?
Width of terminal window, or
nil
if it cannot be determined. -
#wrap_text(str, left_margin, width) ⇒ Object
Wraps text.
Instance Method Details
#pad(str, len, with = " ") ⇒ Object
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_width ⇒ Integer?
Returns Width of terminal window, or nil
if it cannot be determined.
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.
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 |