Class: TermUtil

Inherits:
Object
  • Object
show all
Defined in:
lib/davclient/termutil.rb

Overview

Prompt for password Extracted from Ian Macdonald’s Ruby/Password gem.

Example:

password = getc(message="Password: ", mask='*')
puts "It's:" + password

Class Method Summary collapse

Class Method Details

.echo(on = true, masked = false) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/davclient/termutil.rb', line 14

def self.echo(on=true, masked=false)
  term = Termios::getattr( $stdin )

  if on
    term.c_lflag |= ( Termios::ECHO | Termios::ICANON )
  else # off
    term.c_lflag &= ~Termios::ECHO
    term.c_lflag &= ~Termios::ICANON if masked
  end

  Termios::setattr( $stdin, Termios::TCSANOW, term )
end

.getc(message = "Password: ", mask = '*') ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/davclient/termutil.rb', line 27

def self.getc(message="Password: ", mask='*')
  # Save current buffering mode
  buffering = $stdout.sync

  # Turn off buffering
  $stdout.sync = true

  begin
    echo(false, true)
    print message if message
    pw = ""

    while ( char = $stdin.getc ) != 10 # break after [Enter]
      putc mask
      pw << char
    end

  ensure
    echo true
    print "\n"
  end

  # Restore original buffering mode
  $stdout.sync = buffering

  return pw
end