Class: AskTTY::Internal::Terminal

Inherits:
Object
  • Object
show all
Defined in:
lib/asktty/internal/terminal.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input:, output:) ⇒ Terminal

Returns a new instance of Terminal.



16
17
18
19
20
21
22
23
24
# File 'lib/asktty/internal/terminal.rb', line 16

def initialize(input:, output:)
  @input = input
  @output = output
  @line_count = 0
  @width = output.winsize[1]
  @width = 80 if @width.nil? || @width <= 0
rescue StandardError
  @width = 80
end

Instance Attribute Details

#widthObject (readonly)

Returns the value of attribute width.



8
9
10
# File 'lib/asktty/internal/terminal.rb', line 8

def width
  @width
end

Class Method Details

.openObject

Raises:



10
11
12
13
14
# File 'lib/asktty/internal/terminal.rb', line 10

def self.open(&)
  raise AskTTY::Error, "interactive prompts require a TTY input and output" unless $stdin.tty? && $stdout.tty?

  new(input: $stdin, output: $stdout).open(&)
end

Instance Method Details

#openObject



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/asktty/internal/terminal.rb', line 26

def open
  @output.print "\e[?25l"
  @output.flush

  @input.raw do
    yield self
  end
ensure
  @line_count = 0
  @output.print "\e[0m\r\n\e[?25h"
  @output.flush
end

#read_keyObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/asktty/internal/terminal.rb', line 39

def read_key
  character = @input.getch

  case character
  when "\u0003"
    raise Interrupt
  when "\r"
    :enter
  when "\n"
    :ctrl_j
  when "\u007F", "\b"
    :backspace
  when "\e"
    decode_escape_sequence(read_escape_sequence)
  else
    character
  end
end

#render(text) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/asktty/internal/terminal.rb', line 58

def render(text)
  text = text.to_s

  if @line_count > 1
    @output.print "\e[#{@line_count - 1}F"
  else
    @output.print "\r"
  end

  @output.print "\e[J"
  @output.print normalize_output(text)
  @output.flush

  @line_count = [text.split("\n", -1).length, 1].max
end