module ToyRoboSimulator::Validator
Validator
serves to validate operations performed by a Robo
. It is a standalone module but takes arguments and attributes from a Robo
.
Public Instance Methods
moveable?()
click to toggle source
placed?()
click to toggle source
Ensures the Robo
is placed before any other actions are performed. Returns false if no attributes are set for the Robo
, otherwise returns true.
# File lib/toy_robo_simulator/validator.rb, line 31 def placed? if @x && @y && @orientation true else puts 'The Robo is not placed yet. Use PLACE command first.' false end end
valid_placement?()
click to toggle source
Ensures input values of Robo#place
action is valid in type and range. Returns false if it is not valid, otherwise returns true.
# File lib/toy_robo_simulator/validator.rb, line 7 def valid_placement? validate_placement if @errors.any? @errors.each { |message| puts message } @x, @y, @orientation = nil, nil, nil false else @x, @y = @x.to_i, @y.to_i true end end
Private Instance Methods
edge?()
click to toggle source
# File lib/toy_robo_simulator/validator.rb, line 63 def edge? case @orientation when :north @y == @table.y when :east @x == @table.x when :south @y.zero? when :west @x.zero? end end
in_range?(value, max)
click to toggle source
# File lib/toy_robo_simulator/validator.rb, line 55 def in_range?(value, max) value.to_i >= 0 && value.to_i <= max end
int?(value)
click to toggle source
# File lib/toy_robo_simulator/validator.rb, line 51 def int?(value) value.to_s == value.to_i.to_s end
orientation_valid?(orientation)
click to toggle source
# File lib/toy_robo_simulator/validator.rb, line 59 def orientation_valid?(orientation) ORIENTATIONS.include? orientation.downcase.to_sym end
validate_placement()
click to toggle source
# File lib/toy_robo_simulator/validator.rb, line 42 def validate_placement @errors = [] @errors << 'X must be a number' unless int?(@x) @errors << 'Y must be a number' unless int?(@y) @errors << "X must be between 0 and #{@table.x}" unless in_range?(@x, @table.x) @errors << "Y must be between 0 and #{@table.y}" unless in_range?(@y, @table.y) @errors << 'It can only face NORTH, SOUTH, EAST, or WEST' unless orientation_valid?(@orientation) end