Module: Climatic::Utils::Input

Defined in:
lib/climatic/utils/input.rb

Constant Summary collapse

DEFAULT_CONFIRMATION_CHOICES =
{
    true => %w(Yes y),
    false => %w(No n)
}

Instance Method Summary collapse

Instance Method Details

#get_user_confirmation(choices: DEFAULT_CONFIRMATION_CHOICES, default_choice: 'No', prompt: 'Are you sure ?', strict: false) ⇒ Object

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/climatic/utils/input.rb', line 11

def get_user_confirmation(choices: DEFAULT_CONFIRMATION_CHOICES,
                          default_choice: 'No',
                          prompt: 'Are you sure ?',
                          strict: false)

  raise Climatic::Error, 'Invalid choices !' unless choices.is_a? Hash
  values = choices.values.flatten
  raise Climatic::Error, "Invalid default choice '#{default_choice}' !" unless values.include? default_choice
  if Climatic.config[:auto]
    yield if block_given?
    return true
  end
  full_prompt = '%s (%s): ' % [prompt, choices_string(values, default_choice)]
  STDOUT.print full_prompt
  STDOUT.flush
  input = nil
  until values.include? input
    input = STDIN.gets.chomp
    input = default_choice if input.nil? || input.empty?
    unless strict
      input = default_choice unless values.include? input
    end
  end
  choices.each_pair do |res, possible_choices|
    if possible_choices.include? input
      if res and block_given?
        yield
      end
      return res
    end
  end
  raise 'Something wrong happened !'
end

#get_user_input(prompt, default = nil) ⇒ Object



46
47
48
49
50
51
# File 'lib/climatic/utils/input.rb', line 46

def get_user_input(prompt, default=nil)
  full_prompt = (default.nil? or default.empty?) ? "#{prompt}: " : "#{prompt} (default: #{default}): "
  STDOUT.print full_prompt
  STDOUT.flush
  STDIN.gets.chomp
end