class ToyRoboSimulator::Console

The console is responsible for initaing an interactive command line interface for users to access the program.

Constants

AVAILABLE_COMMANDS

Available user-input commands

Attributes

robo[RW]

Public Class Methods

new() click to toggle source

Initializes a CLI that includes a Robo instance.

# File lib/toy_robo_simulator/console.rb, line 12
def initialize
  puts MESSAGE
  @robo = Robo.new
end

Public Instance Methods

run(command) click to toggle source

Analyzes if command is available, and process the command. The command should be separated either by white spaces or commas. However, only commands in AVAILABLE_COMMANDS are allowed.

“` console = ToyRoboSimulator::Console.new console.run('hello world') # => 'unknown command.' console.run('foo, bar') # => 'unknown command.' console.run('exit') # => 'Thank You!' “`

# File lib/toy_robo_simulator/console.rb, line 36
def run(command)
  args = to_args(command)
  if AVAILABLE_COMMANDS.include?(args[0])
    process(args[0], args[1..-1])
  else
    puts WARNING
  end
end
watch() click to toggle source

Starts watching for user input.

# File lib/toy_robo_simulator/console.rb, line 18
def watch
  n = 0
  while cmd = Readline.readline("#{format('%02d', n)}> ", true)
    run(cmd)
    n += 1
  end
end

Private Instance Methods

exit_program() click to toggle source
# File lib/toy_robo_simulator/console.rb, line 65
def exit_program
  puts "\nThank You!\n\n"
  exit
end
process(action, args) click to toggle source

Directly sends the command with arguments to the Robo instance.

# File lib/toy_robo_simulator/console.rb, line 48
def process(action, args)
  case action
  when 'exit'
    exit_program
  when 'help'
    puts HELP
  else
    robo.send(action.to_sym, *args)
  end
rescue ArgumentError => e
  puts TIP if e.message.include? 'wrong number of arguments'
end
to_args(command) click to toggle source
# File lib/toy_robo_simulator/console.rb, line 61
def to_args(command)
  command.split(' ').map { |n| n.split(',') }.flatten.map(&:chomp).map(&:downcase)
end