Class: UserInput::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/userinput.rb

Overview

Prompt object

Instance Method Summary collapse

Constructor Details

#initialize(params = {}, &block) ⇒ Prompt

Build new prompt object and set defaults



18
19
20
21
22
23
24
# File 'lib/userinput.rb', line 18

def initialize(params = {}, &block)
  @attempts = params[:attempts]
  @message = params[:message] || ''
  @default = params[:default]
  @secret = params[:secret] || false
  @validation = block || params[:validation]
end

Instance Method Details

#askObject

Request user input



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/userinput.rb', line 28

def ask
  print "#{@message}? #{@default.nil? ? '' : "[#{@default}] "}"
  disable_echo if @secret

  input = _ask
  return input if valid(input)

  check_counter
  ask
ensure
  enable_echo if @secret
end

#valid(input) ⇒ Object

Validate user input



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/userinput.rb', line 43

def valid(input)
  case @validation
  when Proc
    return @validation.call input
  when Regexp
    return @validation.match input
  when NilClass
    return true
  else
    fail "Supported validation type not provided #{@validation.class}"
  end
end