Class: Zenflow::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/zenflow/helpers/ask.rb

Class Method Summary collapse

Class Method Details

.ask_question(question, options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/zenflow/helpers/ask.rb', line 18

def self.ask_question(question, options={})
  if options[:response].to_s.strip != ""
    response = options[:response]
  else
    response = Zenflow::Query.prompt_for_answer(question, options)
  end
  Zenflow::LogToFile("Response: #{response}")
  response
end

.build_error_message(response, options = {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/zenflow/helpers/ask.rb', line 57

def self.build_error_message(response, options={})
  if options[:required]
    message = "You must respond to this prompt."
  elsif options[:error_message]
    message = options[:error_message]
  else
    message = %{"#{response}" is not a valid response.}
  end
  "-----> #{message} Try again.".red
end

.handle_response(response, options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/zenflow/helpers/ask.rb', line 37

def self.handle_response(response, options={})
  if !Zenflow::Query.valid_response?(response, options)
    raise Zenflow::Query.build_error_message(response, options)
  end

  return options[:default].downcase if response == ""
  return response.downcase if response == "Y" || response == "N"
  response
end

.prompt_for_answer(question, options = {}) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/zenflow/helpers/ask.rb', line 28

def self.prompt_for_answer(question, options={})
  prompt = ">> #{question} "
  prompt << "[#{options[:options].join('/')}] " if options[:options]
  prompt << "[#{options[:default]}] " if options[:default] && !options[:options]
  Zenflow::LogToFile("Asked: #{prompt}")
  print prompt
  $stdin.gets.chomp
end

.valid_response?(response, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
54
55
# File 'lib/zenflow/helpers/ask.rb', line 47

def self.valid_response?(response, options={})
  response = normalize_response(response, options[:default])
  options[:options].map!(&:downcase) if options[:options]

  return false if options[:options] && !options[:options].include?(response)
  return false if options[:validate] && options[:validate].is_a?(Regexp) && !response[options[:validate]]
  return false if options[:required] && response == ""
  true
end