Permalink
Browse files

adds question traversal logic to state

  • Loading branch information...
Najaf committed Feb 27, 2013
1 parent e55d918 commit 78c1e5fe3ce3298a16f5fc77fee43d475d946115
Showing with 67 additions and 6 deletions.
  1. +16 −0 lib/dumb-answers/state.rb
  2. +28 −6 spec/data/state-test.yml
  3. +23 −0 spec/state_spec.rb
View
@@ -16,5 +16,21 @@ class State
def initialize(nodes, initial_node_id)
@nodes, @history, @current = nodes, [], nodes[initial_node_id]
end
+
+ def answer!(question_id, answer_code)
+ @history << [question_id, answer_code]
+
+ # determine the applicable transitions by evaluating
+ # the history against a list of possible transitions from
+ # the current node
+ applicable_transitions = @current.transitions.select do |transition|
+ transition['conditions'].each_pair.all? do |question_id, answer_code|
+ @history.include? [question_id, answer_code]
+ end
+ end
+
+ next_node_id = applicable_transitions.first['next']
+ @current = @nodes[next_node_id]
+ end
end
end
View
@@ -3,13 +3,35 @@
text: "Do you like cheese?"
additional_text: "Some more text"
answers:
- a: 'yes'
- b: 'no'
+ a: 'Yes'
+ b: 'No'
transitions:
- - conditions: { 'test-question-1': 'a' }
- id: 'test-ending'
- - conditions: { 'test-question-1': 'b' }
- id: 'test-ending'
+ - conditions: { 'q1': 'a' }
+ next: 'q2'
+ - conditions: { 'q1': 'b' }
+ next: 'q3'
+- id: 'q2'
+ type: question
+ text: "Which of the following is the best?"
+ additional_text: "Some more text"
+ answers:
+ a: 'Gogonzola'
+ b: 'Parmesan'
+ c: 'Cheddar'
+ d: 'Brie'
+ transitions:
+ - conditions: { 'q1': 'a' }
+ next: 'e1'
+- id: 'q3'
+ type: question
+ text: "Are you sure?"
+ additional_text: "Some more text"
+ answers:
+ a: 'Yes'
+ b: 'No'
+ transitions:
+ - conditions: { 'q1': 'b' }
+ next: 'e1'
- id: 'e1'
type: 'ending'
text: 'Good for you!'
View
@@ -19,4 +19,27 @@
@state.current.must_equal @nodes['q1']
end
end
+
+ describe '#answer!' do
+ before do
+ @nodes = YamlParser.load(test_data('state-test'))
+ @state = State.new(@nodes, 'q1')
+ end
+
+ it 'adds the question/answerpair to history' do
+ @state.answer! 'q1', 'a'
+ @state.history.must_include %w(q1 a)
+ end
+
+ it 'moves current to next matching question' do
+ @state.answer! 'q1', 'a'
+ @state.current.must_equal @nodes['q2']
+ end
+
+ it 'does all of the above for the other path' do
+ @state.answer! 'q1', 'b'
+ @state.history.must_include %w(q1 b)
+ @state.current.must_equal @nodes['q3']
+ end
+ end
end

0 comments on commit 78c1e5f

Please sign in to comment.