Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created January 23, 2017 10:08
Show Gist options
  • Save wojtha/8829678f973d3b8a546018fe08f2708e to your computer and use it in GitHub Desktop.
Save wojtha/8829678f973d3b8a546018fe08f2708e to your computer and use it in GitHub Desktop.
Class Question::MultipleChoice is a simple, closed-ended question type that lets respondents select one or multiple answers from a defined list of choices.
# Class Question::MultipleChoice is a simple, closed-ended question type that lets respondents select one or multiple
# answers from a defined list of choices.
#
# @example Definition
# question = Question::MultipleChoice.new("Reference doesn't seem to be regular release. MAKE A BUILD?")
# .choice(:build, 'b', '[b]uild')
# .choice(:install, 'i', '[i]nstall and build')
# .choice(:clean, 'c', '[c]lean install and build')
# .choice(:skip, 's', '[s]kip')
# .choice(:quit, 'q', '[q]uit')
#
# answer = question.ask
#
# case answer
# when :build
# puts '=>>>> [b]uild'
# when :install
# puts '=>>>> [i]nstall and build'
# when :clean
# puts '=>>>> [c]lean install and build'
# when :skip
# puts '=>>>> [s]kip'
# when :quit
# puts '=>>>> [q]uit'
# end
#
# @example Result
#
# Reference doesn't seem to be regular release. MAKE A BUILD?
# [b]uild'
# [i]nstall and build'
# [c]lean install and build'
# [s]kip'
# [q]uit'
#
module Question
class MultipleChoice
Choice = Struct.new(:name, :shortkey, :label)
attr_reader :question, :choices
def initialize(question, choices = [])
@question = question
@choices = choices
end
def choice(name, shortkey, label)
@choices << Choice.new(name, shortkey, label)
self
end
def ask
answer = loop do
$stdout.puts render
input = $stdin.gets.chomp
next if input.size.zero?
choice = find_choice(input)
break choice if choice
end
answer.name
end
def ask_with_inquiry
ActiveSupport::StringInquirer.new(ask.to_s)
end
def render
"\e[33m#{render_question}#{render_choices}\e[0m"
end
protected
def find_choice(input)
choices.find { |o| o.shortkey.to_s == input || o.name.to_s == input }
end
def render_question
question
end
def render_choices
"\n " + choices.map(&:label).join("\n ")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment