Module: Interactive

Included in:
Rewindable
Defined in:
lib/interact/interactive.rb

Overview

Copyright © 2012 Alex Suraci

Defined Under Namespace

Modules: Rewindable Classes: InputState

Constant Summary collapse

EVENTS =
{
  "\b" => :backspace,
  "\t" => :tab,
  "\x01" => :home,
  "\x03" => :interrupt,
  "\x04" => :eof,
  "\x05" => :end,
  "\x17" => :kill_word,
  "\x7f" => :backspace,
  "\r" => :enter,
  "\n" => :enter
}
ESCAPES =
{
  "[A" => :up, "H" => :up,
  "[B" => :down, "P" => :down,
  "[C" => :right, "M" => :right,
  "[D" => :left, "K" => :left,
  "[3~" => :delete, "S" => :delete,
  "[H" => :home, "G" => :home,
  "[F" => :end, "O" => :end,
  "[Z" => :shift_tab
}

Instance Method Summary collapse

Instance Method Details

#ask(question, options = {}) ⇒ Object

Ask a question and get an answer.

See Interact#read_line for the other possible values in options.

question

The prompt, without “: ” at the end.

options

An optional hash containing the following options.

default

The default value, also used to attempt type conversion of the answer (e.g. numeric/boolean).

choices

An array (or Enumerable) of strings to choose from.

indexed

Use alternative choice listing, and allow choosing by number. Good for when there are many choices or choices with long names.



172
173
174
175
176
177
178
179
180
181
182
# File 'lib/interact/interactive.rb', line 172

def ask(question, options = {})
  choices = options[:choices] && options[:choices].to_a

  list_choices(choices, options) if choices

  while true
    prompt(question, options)
    ok, res = answered(read_line(options), options)
    return res if ok
  end
end

#read_char(options = {}) ⇒ Object

Read a single character.

options

An optional hash containing the following options.

input

The input source (defaults to $stdin).



109
110
111
112
113
114
115
# File 'lib/interact/interactive.rb', line 109

def read_char(options = {})
  input = options[:input] || $stdin

  with_char_io(input) do
    get_character(input)
  end
end

#read_event(options = {}) ⇒ Object

Read a single event.

options

An optional hash containing the following options.

input

The input source (defaults to $stdin).



123
124
125
126
127
128
129
# File 'lib/interact/interactive.rb', line 123

def read_event(options = {})
  input = options[:input] || $stdin

  with_char_io(input) do
    get_event(input)
  end
end

#read_line(options = {}) ⇒ Object

Read a line of input.

options

An optional hash containing the following options.

input

The input source (defaults to $stdin).

echo

A string to echo when showing the input; used for things like hiding password input.



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/interact/interactive.rb', line 141

def read_line(options = {})
  input = options[:input] || $stdin

  state = input_state(options)
  with_char_io(input) do
    until state.done?
      handler(get_event(input), state)
    end
  end

  state.answer
end