Commit 45f2f6a

mo k <mo@mokhan.ca>
2012-11-07 04:06:56
refactor explicit instructions to a model where new instructions can be added to the system with ease.
1 parent 6c713fa
lib/filtered_command.rb
@@ -0,0 +1,10 @@
+class FilteredCommand
+  def initialize(command, specification)
+    @command = command
+    @specification = specification
+  end
+  def run(item)
+    @command.run if @specification.matches(item)
+  end
+end
+
lib/move_forward.rb
@@ -6,22 +6,3 @@ class MoveForward
     @rover.drive
   end
 end
-
-class FilteredCommand
-  def initialize(command, specification)
-    @command = command
-    @specification = specification
-  end
-  def run(item)
-    @command.run if @specification.matches(item)
-  end
-end
-
-class Specification
-  def initialize(criteria)
-    @criteria = criteria
-  end
-  def matches(item)
-    @criteria.call(item)
-  end
-end
lib/navigate_rover.rb
@@ -1,4 +1,6 @@
 require "plateau"
+require "specification"
+require "filtered_command"
 require "move_forward"
 require "turn_left"
 require "turn_right"
@@ -28,9 +30,14 @@ class NavigateRover
   end
 
   def commands_for(rover)
-    [move_forward(rover), TurnLeft.new(rover), TurnRight.new(rover)]
+    [
+      create_command_for(rover, eval("MoveForward"), 'M'),
+      create_command_for(rover, eval("TurnLeft"), 'L'),
+      create_command_for(rover, eval("TurnRight"), 'R')
+    ]
   end
-  def move_forward(rover)
-    FilteredCommand.new(MoveForward.new(rover), Specification.new(lambda { |x| 'M' == x.upcase }))
+
+  def create_command_for(rover, command, instruction)
+    FilteredCommand.new(command.new(rover), Specification.new(lambda { |x| instruction == x.upcase }))
   end
 end
lib/specification.rb
@@ -0,0 +1,8 @@
+class Specification
+  def initialize(criteria)
+    @criteria = criteria
+  end
+  def matches(item)
+    @criteria.call(item)
+  end
+end
lib/turn_left.rb
@@ -2,10 +2,7 @@ class TurnLeft
   def initialize(rover)
     @rover = rover
   end
-  def run(instruction)
-    @rover.rotate(-90) if matches(instruction)
-  end
-  def matches(item)
-    'L' == item.upcase
+  def run
+    @rover.rotate(-90)
   end
 end
lib/turn_right.rb
@@ -2,10 +2,7 @@ class TurnRight
   def initialize(rover)
     @rover = rover
   end
-  def run(instruction)
-    @rover.rotate(90) if matches(instruction)
-  end
-  def matches(item)
-    'R' == item.upcase
+  def run
+    @rover.rotate(90)
   end
 end