Sha256: 00cefcbb93c7fc49ba0a04a750cca691964ba9a079169fd2fdac9cc7d64b28ee

Contents?: true

Size: 1.17 KB

Versions: 2

Compression:

Stored size: 1.17 KB

Contents

# This class implements the proxy design pattern. It sits between the client and the commands,
# and only invokes the command if it passes validation.
module Robot
  class CommandProxy

    attr_reader :command_string, :position, :min_point, :max_point

    def initialize(command_string:, position: nil)
      @command_string = command_string
      @position = position
    end

    def call
      return if not_placed_yet? && !place_command?
      return position if would_fall?

      execute
    end

    private

    def execute
      if place_command?
        command_class.build_from_string_command(command_string)
      else
        command_class.(position)
      end
    end

    def command_class
      Robot::Commands::Factory.build(command_string)
    end

    def would_fall?
      return unless [Robot::Commands::Move, Robot::Commands::Place].include?(command_class)
      new_position = execute
      new_position.point > table.max_point || new_position.point < table.min_point
    end

    def table
      @table ||= Robot::Table.new
    end

    def not_placed_yet?
      position.nil?
    end

    def place_command?
      command_class == Robot::Commands::Place
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
robot_rea-0.1.5 lib/robot/command_proxy.rb
robot_rea-0.1.4 lib/robot/command_proxy.rb