Class: T_BAG::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/tbag/prompt.rb

Overview

Defines a prompt and its run behavior.

Instance Method Summary collapse

Constructor Details

#initialize(question, type, error) ⇒ Prompt

Returns a new instance of Prompt.

Parameters:

  • question (String)

    the prompt for the User

  • type (ANY)

    the type of the expected User input

  • error (String)

    the error to display if User input is invalid



35
36
37
38
39
40
# File 'lib/tbag/prompt.rb', line 35

def initialize(question, type, error)
  @question = question
  @type = type
  @choices = {}
  @error = error
end

Instance Method Details

#choice(value, &block) ⇒ Object

Capture the User’s answer to a prompt

Parameters:

  • value (String)

    the User input

  • block (Block)


45
46
47
48
49
50
# File 'lib/tbag/prompt.rb', line 45

def choice(value, &block)
  if value.is_a? String
    value.downcase!
  end
  @choices[value] = Proc.new &block
end

#runObject

Define how to interpret prompt input.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/tbag/prompt.rb', line 53

def run
  puts @question
  done = false
  until done
    answer = gets.strip

    if @type == Integer
      unless answer.to_i == 0
        answer = answer.to_i
      end
    elsif @type == String
      answer.downcase!
    end
    if answer.is_a? @type and (@choices[answer] or @choices[:any])
      if @choices[answer]
        @choices[answer].call(answer)
      else
        @choices[:any].call(answer)
      end
      done = true
    else
      puts @error
    end
  end
end