Module: Clio::Terminal

Defined in:
lib/clio/consoleutils.rb

Overview

Termninal

ConsoleUtils provides methods that are generally useful in the context of creating console output.

Class Method Summary collapse

Class Method Details

.ask(question, answers = nil) ⇒ Object

Convenient method to get simple console reply.



15
16
17
18
19
20
# File 'lib/clio/consoleutils.rb', line 15

def ask(question, answers=nil)
  print "#{question}"
  print " [#{answers}] " if answers
  until inp = $stdin.gets ; sleep 1 ; end
  inp
end

.password(msg = nil) ⇒ Object

Ask for a password. (FIXME: only for unix so far)



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/clio/consoleutils.rb', line 32

def password(msg=nil)
  msg ||= "Enter Password: "
  inp = ''

  $stdout << msg

  begin
    system "stty -echo"
    inp = gets.chomp
  ensure
    system "stty echo"
  end

  return inp
end

Print a justified line with left and right entries.

A fill option can be given to fill in any empty space between the two. And a ratio option can be given which defaults to 0.8 (eg. 80/20)



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/clio/consoleutils.rb', line 74

def print_justified(left, right, options={})
  fill  = options[:fill] || '.'
  fill  = ' ' if fill == ''
  fill  = fill[0,1]

  ratio = options[:ratio] || 0.8
  ratio = 1 + ratio if ratio < 0

  width = (@screen_width ||= screen_width) - 1

  #l = (width * ratio).to_i
  r = (width * (1 - ratio)).to_i
  l = width - r

  left  = left[0,l]
  right = right[0,r]

  str = fill * width
  str[0,left.size] = left
  str[width-right.size,right.size] = right

  print str
end

.screen_width(out = STDERR) ⇒ Object

Console screen width (taken from progress bar)

TODO: Don’t know how portable #screen_width is.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/clio/consoleutils.rb', line 52

def screen_width(out=STDERR)
  default_width = ENV['COLUMNS'] || 80
  begin
    tiocgwinsz = 0x5413
    data = [0, 0, 0, 0].pack("SSSS")
    if out.ioctl(tiocgwinsz, data) >= 0 then
      rows, cols, xpixels, ypixels = data.unpack("SSSS")
      if cols >= 0 then cols else default_width end
    else
      default_width
    end
  rescue Exception
    default_width
  end
end