Class: Worlds::Terminal::Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/worlds/terminal/helper.rb

Overview

Utility methods for allowing output above the input line in the terminal.

Class Method Summary collapse

Class Method Details

.hide_cursor!Object

From stackoverflow.com/a/50152099 If the cursor weren’t hidden, it would appear at the beginning of the line due to ::io_mode_raw!



12
# File 'lib/worlds/terminal/helper.rb', line 12

def self.hide_cursor! = print "\033[?25l"

.io_mode_normal!Object



7
# File 'lib/worlds/terminal/helper.rb', line 7

def self.io_mode_normal! = `stty -raw`

.io_mode_raw!Object

To allow output above the input line, disables input buffering.



6
# File 'lib/worlds/terminal/helper.rb', line 6

def self.io_mode_raw! = `stty raw`

.puts(str) ⇒ Object

To allow output above the input line, wraps ‘puts` in a change to the terminal mode. Also right-pads the output with spaces to prevent the input from “bleeding over” into output wherever an output line is shorter than a line being inputted.



32
33
34
35
36
37
38
39
# File 'lib/worlds/terminal/helper.rb', line 32

def self.puts(str)
  # From https://gist.github.com/KINGSABRI/4687864
  terminal_width = `tput cols`.to_i

  io_mode_normal!
  Kernel.puts str.ljust(terminal_width, ' ')
  io_mode_raw!
end

.read_nonblockString

Reads newly inputted characters in a way that doesn’t block output, to allow output above the input line. Based on stackoverflow.com/a/9900628

Returns:

  • (String)

    all inputted characters.



18
19
20
21
22
23
24
25
# File 'lib/worlds/terminal/helper.rb', line 18

def self.read_nonblock
  line = ''

  while char = STDIN.read_nonblock(1, exception: false)
    return line if char == :wait_readable
    line << char
  end
end

.show_cursor!Object



13
# File 'lib/worlds/terminal/helper.rb', line 13

def self.show_cursor! = print "\033[?25h"