ConsoleUtils

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

Methods
Public Instance methods
ask(question, answers=nil)

Convenient method to get simple console reply.

# File lib/facets/consoleutils.rb, line 29
  def ask(question, answers=nil)
    print "#{question}"
    print " [#{answers}] " if answers
    until inp = $stdin.gets ; sleep 1 ; end
    inp
  end
password(msg=nil)

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

# File lib/facets/consoleutils.rb, line 46
  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_justified(left, right, options={})

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)

# File lib/facets/consoleutils.rb, line 88
  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)

Console screen width (taken from progress bar)

TODO: Don‘t know how portable screen_width is.

# File lib/facets/consoleutils.rb, line 66
  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