Class: Playmo::Choice

Inherits:
Object show all
Defined in:
lib/playmo/choice.rb

Constant Summary collapse

CAPTION =
"Your choice"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(question) ⇒ Choice

Returns a new instance of Choice.



6
7
8
9
10
# File 'lib/playmo/choice.rb', line 6

def initialize(question)
  @question = question
  @shell    = Thor::Shell::Basic.new
  @color    = Thor::Shell::Color.new
end

Instance Attribute Details

#colorObject

Returns the value of attribute color.



4
5
6
# File 'lib/playmo/choice.rb', line 4

def color
  @color
end

#questionObject

Returns the value of attribute question.



4
5
6
# File 'lib/playmo/choice.rb', line 4

def question
  @question
end

#shellObject

Returns the value of attribute shell.



4
5
6
# File 'lib/playmo/choice.rb', line 4

def shell
  @shell
end

#user_inputObject

Returns the value of attribute user_input.



4
5
6
# File 'lib/playmo/choice.rb', line 4

def user_input
  @user_input
end

Instance Method Details

#accepted_valuesObject



12
13
14
15
16
17
18
# File 'lib/playmo/choice.rb', line 12

def accepted_values
  if question.has_answers?
    1.upto(question.answers.size).to_a.map { |value| value.to_s }
  else
    %w/y n yes no/
  end
end

#get_answerObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/playmo/choice.rb', line 20

def get_answer
  shell.padding = 1
  answer = nil

  until accepted_values.include?(@user_input) do
    @user_input = shell.ask(render)
    @user_input.downcase!
  end

  if @user_input
    if question.has_answers?
      answer = question.answers.find { |answer| answer.num.to_s == @user_input }
    else
      answer = question.answers.first if %w/y yes/.include?(@user_input)
    end
  end

  answer
end

#renderObject Also known as: to_s



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/playmo/choice.rb', line 40

def render
  if question.has_answers?
    sentence = accepted_values.to_sentence(
      :last_word_connector => ' or '
    )
  else
    sentence = "y/n"
  end

  color.set_color("#{CAPTION} (#{sentence}):", :white, true)
end