Class: InputDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/fresnel/input_detector.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(question, *answers) ⇒ InputDetector

Returns a new instance of InputDetector.



4
5
6
7
8
9
10
11
12
13
# File 'lib/fresnel/input_detector.rb', line 4

def initialize(question,*answers)
  @question=question
  @possible_answers=Array.new
  @possible_answers+=question.scan(/\[(.*?)\]/).flatten
  @possible_answers+=answers.flatten
  @collection=""
  @answer=""
  print question
  detect_answer
end

Instance Attribute Details

#answerObject

Returns the value of attribute answer.



2
3
4
# File 'lib/fresnel/input_detector.rb', line 2

def answer
  @answer
end

#collectionObject

Returns the value of attribute collection.



2
3
4
# File 'lib/fresnel/input_detector.rb', line 2

def collection
  @collection
end

#possible_answersObject

Returns the value of attribute possible_answers.



2
3
4
# File 'lib/fresnel/input_detector.rb', line 2

def possible_answers
  @possible_answers
end

#questionObject

Returns the value of attribute question.



2
3
4
# File 'lib/fresnel/input_detector.rb', line 2

def question
  @question
end

Class Method Details

.pretty_prompt(inputs, *extras) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/fresnel/input_detector.rb', line 15

def self.pretty_prompt(inputs, *extras)
  lines = inputs.keys.sort_by(&:to_s).map do |key|
    choices = inputs[key].sort.map {|state| '[%s]%s' % [state[0,1], state[1..-1]]}.join(", ")
    "#{key.to_s.capitalize}: #{choices}"
  end
  prompt = lines.join(".\n") + ": "
  new(prompt, *extras)
end

Instance Method Details

#detect_answerObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/fresnel/input_detector.rb', line 24

def detect_answer
  loop do
    begin
      system("stty raw -echo")
      str = STDIN.getc
    ensure
      system("stty -raw echo")
    end
    print str.chr
    if str == 13
      puts
      exit if collection.blank?
      possible_options = possible_answers.select{|option| option == collection}
    else
      self.collection+=str.chr
      possible_options = possible_answers.select{|option| option.to_s =~ /^#{collection}/}
    end
    if possible_options.size == 0
      if str==3
        puts
        puts "exiting due to ^c"
        exit
      end
      puts
      puts "Invalid choice: #{collection}, choises are #{possible_answers.inspect}"
      print question
      self.collection=""
    elsif possible_options.size == 1
      collection = possible_options.first
      self.answer=collection.to_s
      puts
      break
    else
      next
    end
  end
end