From 8db825300d2d0f46dc65addea53375e9209581ec Mon Sep 17 00:00:00 2001 From: Dmitry Maksyoma Date: Sun, 6 Apr 2014 21:14:35 +1200 Subject: [PATCH] * Refactor. Use a specific exception instead of ArgumentError, thus saving us from: * Rescuing errors we didn't mean to rescue OR * Having an ugly being-rescue block at the start of #place. --- robot.rb | 2 +- spec/state_spec.rb | 5 +++++ state.rb | 4 ++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/robot.rb b/robot.rb index 79de386..056bc04 100644 --- a/robot.rb +++ b/robot.rb @@ -54,7 +54,7 @@ def place x, y, direction return unless @@table.contain? new_coords.x, new_coords.y @coords = new_coords - rescue ArgumentError + rescue StateArgumentError end def report diff --git a/spec/state_spec.rb b/spec/state_spec.rb index 9e55af8..c976172 100644 --- a/spec/state_spec.rb +++ b/spec/state_spec.rb @@ -6,4 +6,9 @@ state = Robot::State.new 0, 0, 'NORTH' expect(state.to_s).to eq '0,0,NORTH' end + + it 'raises State if a constructor argument is invalid' do + expect { Robot::State.new 'a', 0, 'NORTH' }.to \ + raise_error Robot::StateArgumentError + end end diff --git a/state.rb b/state.rb index 9138050..f0fb92a 100644 --- a/state.rb +++ b/state.rb @@ -1,10 +1,14 @@ require './direction' class Robot + class StateArgumentError < ArgumentError; end + State = Struct.new(:x, :y, :direction) do def initialize x, y, direction self.x, self.y, self.direction = Integer(x), Integer(y), Direction(direction) + rescue ArgumentError + raise StateArgumentError, $!.message end def to_s