Module: MakeMenu::Console::Prompter

Defined in:
lib/make_menu/console/prompter.rb

Constant Summary collapse

PressedEscape =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.prompt(text = '', input: '', obscure: false, value_color: :light_yellow) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/make_menu/console/prompter.rb', line 28

def self.prompt(text = '', input: '', obscure: false, value_color: :light_yellow)
  text = text.bold

  print "\r#{text}#{input.color(value_color)}"

  char = ''

  until !char.empty? && char.ord == 13
    char = $stdin.getch

    case char.ord
    when 127
      # BACKSPACE
      input = input[0..-2]
      print "\r#{text}#{' ' * input.size} "
      print "\r#{text}#{obscure ? '*'.color(value_color) * input.size : input.color(value_color)}"

    when 27
      # ESC
      raise PressedEscape if input.empty?

      print "\r#{text}#{' ' * input.size} "
      print "\r#{text}"

      input = ''
      char = ''

    when 13
      # ENTER

    else
      input += char
      if obscure
        print '*'.color(value_color)
      else
        print char.color(value_color)
      end
    end
  end

  print "\r#{text}#{' ' * input.size} "
  print "\r#{text}"

  input
end

.prompt_and_save(text, file:, obscure: false) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/make_menu/console/prompter.rb', line 10

def self.prompt_and_save(text, file:, obscure: false)
  if file.is_a? Symbol
    file = ".#{file}"
  end

  current = File.exist?(file) ? File.read(file).strip : ''

  response = prompt(text, input: current, obscure: obscure)

  if response.empty?
    File.delete(file) if File.exist?(file)
  else
    File.write(file, response)
  end

  return response
end