Commit 6c713fa

mo k <mo@mokhan.ca>
2012-11-07 03:56:43
extract FilteredCommand and Specification.
1 parent d4cfc70
lib/move_forward.rb
@@ -2,12 +2,26 @@ class MoveForward
   def initialize(rover)
     @rover = rover
   end
-  def run(instruction)
-    if matches(instruction)
-      @rover.drive
-    end
+  def run
+    @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)
-    'M' == item.upcase
+    @criteria.call(item)
   end
 end
lib/navigate_rover.rb
@@ -9,6 +9,7 @@ class NavigateRover
     @x, @y, @heading = starting_position.split()
     @instructions = instructions.split(//)
   end
+
   def run
     rover = create_plateau(@plateau_size).deploy_rover_to(@heading, @x.to_i, @y.to_i)
     @instructions.each do |instruction|
@@ -18,11 +19,18 @@ class NavigateRover
     end
     rover.to_s
   end
+
+  private
+
   def create_plateau(plateau_size)
     x,y = plateau_size.split(' ')
     Plateau.new(x,y)
   end
+
   def commands_for(rover)
-    [MoveForward.new(rover), TurnLeft.new(rover), TurnRight.new(rover)]
+    [move_forward(rover), TurnLeft.new(rover), TurnRight.new(rover)]
+  end
+  def move_forward(rover)
+    FilteredCommand.new(MoveForward.new(rover), Specification.new(lambda { |x| 'M' == x.upcase }))
   end
 end
spec/features/navigation.feature
@@ -14,6 +14,7 @@ Feature: Navigation
       | x | y | starting_position | instructions  | result |
       | 5 | 5 | 1 2 N             | LMLMLMLMM     | 1 3 N  |
       | 5 | 5 | 3 3 E             | MMRMMRMRRM    | 5 1 E  |
+      | 5 | 5 | 3 3 E             | MmRmMrMrRm    | 5 1 E  |
       | 1 | 1 | 0 0 N             | M    | 0 1 N  |
       | 1 | 1 | 0 0 E             | M    | 1 0 E  |
       | 1 | 1 | 0 0 W             | M    | 1 0 W  |