Class: TTY::Shell::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/shell/reader.rb

Overview

A class responsible for reading character input from STDIN

Constant Summary collapse

CARRIAGE_RETURN =

Key input constants for decimal codes

13.freeze
NEWLINE =
10.freeze
BACKSPACE =
127.freeze
DELETE =
8.freeze

Instance Method Summary collapse

Constructor Details

#initialize(shell = nil) ⇒ Reader

Initialize a Reader



22
23
24
# File 'lib/tty/shell/reader.rb', line 22

def initialize(shell=nil)
  @shell = shell || Shell.new
end

Instance Method Details

#buffer(&block) ⇒ Object

Get input in unbuffered mode.



30
31
32
33
34
35
36
37
38
39
# File 'lib/tty/shell/reader.rb', line 30

def buffer(&block)
  bufferring = shell.output.sync
  # Immediately flush output
  shell.output.sync = true

  value = block.call if block_given?

  shell.output.sync = bufferring
  value
end

#getc(mask = (not_set=true)) ⇒ String

Get a value from STDIN one key at a time. Each key press is echoed back to the shell masked with character(if given). The input finishes when enter key is pressed.

Parameters:

  • mask (String) (defaults to: (not_set=true))

    the character to use as mask

Returns:

  • (String)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/tty/shell/reader.rb', line 51

def getc(mask=(not_set=true))
  value = ""

  buffer do
    begin
      while (char = shell.input.getbyte) and
          !(char == CARRIAGE_RETURN || char == NEWLINE)

        if (char == BACKSPACE || char == DELETE)
          value.slice!(-1, 1) unless value.empty?
        else
          print_char char, not_set, mask
          value << char
        end
      end
    ensure
      TTY.terminal.echo_on
    end
  end

  value
end

#getsObject

Get a value from STDIN using line input.



77
78
79
# File 'lib/tty/shell/reader.rb', line 77

def gets
  shell.input.gets
end