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 = Shell.new) ⇒ Reader

Initialize a Reader



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

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

Instance Method Details

#buffer(&block) ⇒ String

Get input in unbuffered mode.

Examples:

buffer do
  ...
end

Returns:

  • (String)


35
36
37
38
39
40
41
42
43
44
# File 'lib/tty/shell/reader.rb', line 35

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)


56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tty/shell/reader.rb', line 56

def getc(mask = (not_set = true))
  value = ''
  buffer do
    begin
      while (char = shell.input.getbyte) &&
          !(char == CARRIAGE_RETURN || char == NEWLINE)
        value = handle_char value, char, not_set, mask
      end
    ensure
      TTY.terminal.echo_on
    end
  end
  value
end

#getsObject

Get a value from STDIN using line input.



74
75
76
# File 'lib/tty/shell/reader.rb', line 74

def gets
  shell.input.gets
end