Class: Babushka::Prompt

Inherits:
Object show all
Extended by:
LogHelpers
Defined in:
lib/babushka/prompt.rb

Defined Under Namespace

Modules: Helpers

Class Method Summary collapse

Methods included from LogHelpers

debug, deprecated!, log, log_block, log_error, log_ok, log_stderr, log_warn, removed!

Class Method Details

.confirm(message, opts = {}, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/babushka/prompt.rb', line 38

def confirm message, opts = {}, &block
  prompter = (!opts[:always_ask] && respond_to?(:var)) ? :var : :get_value
  answer = send(prompter, message,
    :message => message,
    :confirmation => true,
    :default => (opts[:default] || 'y')
  ).starts_with?('y')

  if block.nil?
    answer
  elsif answer
    block.call
  elsif opts[:otherwise]
    log opts[:otherwise]
  end
end

.get_ip(message, opts = {}) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/babushka/prompt.rb', line 55

def get_ip message, opts = {}
  get_value(message, opts.merge(
    :retry => "That's not an IP, like '10.0.1.1'."
  )) {|value|
    IP.new(value).valid?
  }
end

.get_ip_range(message, opts = {}) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/babushka/prompt.rb', line 63

def get_ip_range message, opts = {}
  get_value(message, opts.merge(
    :retry => "That's not an IP range, like '10.0.1.x'."
  )) {|value|
    IPRange.new(value).valid?
  }
end

.get_path(message, opts = {}) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/babushka/prompt.rb', line 71

def get_path message, opts = {}
  get_value(message, opts.merge(
    :retry => "Doesn't exist, or not a directory."
  )) {|value|
    (value || '').p.dir?
  }
end

.get_value(message, opts = {}, &block) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/babushka/prompt.rb', line 79

def get_value message, opts = {}, &block
  if opts[:choices] && opts[:choice_descriptions]
    raise ArgumentError, "You can't use the :choices and :choice_descriptions options together."
  elsif opts[:choice_descriptions]
    opts[:choices] = opts[:choice_descriptions].keys
  end
  if opts[:choices] && opts[:choices].any? {|c| !c.is_a?(String) }
    raise ArgumentError, "Choices must be passed as strings."
  end
  opts.defaults! :prompt => '? '
  prompt_and_read_value prompt_message(message, opts), opts.merge(:ask => !Base.task.opt(:defaults)), &block
end

.suggest_value_for(typo, choices) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/babushka/prompt.rb', line 25

def suggest_value_for typo, choices
  if (possible_matches = choices.similar_to(typo.to_s)).empty?
    nil # nothing to suggest
  elsif possible_matches.length == 1
    confirm "#{"Did you mean".colorize('grey')} '#{possible_matches.first}'#{"?".colorize('grey')}" do
      possible_matches.first
    end or false
  else
    log "Similar: #{possible_matches.map {|d| "'#{d}'" }.join(', ')}"
    get_value("Did you mean any of those".colorize('grey'), :default => possible_matches.first)
  end
end