Class: Pantry::CommandHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/pantry/command_handler.rb

Overview

Manages and processes commands as requested from the Client or the Server. Given a mapping of available commands, maps the incoming message to the appropriate command handler and returns the response. Returns nil if no command found.

Instance Method Summary collapse

Constructor Details

#initialize(server_or_client, commands_to_register = []) ⇒ CommandHandler

Returns a new instance of CommandHandler.



8
9
10
11
12
13
14
15
# File 'lib/pantry/command_handler.rb', line 8

def initialize(server_or_client, commands_to_register = [])
  @handlers = {}
  @server_or_client = server_or_client

  commands_to_register.each do |command_class|
    add_command(command_class)
  end
end

Instance Method Details

#add_command(command_class) ⇒ Object

Install a Command class as a message handler for this process. The Message’s type for this kind of message is simply the name of the class without any scope information. E.g. Echo not Pantry::Command::Echo.



20
21
22
# File 'lib/pantry/command_handler.rb', line 20

def add_command(command_class)
  @handlers[command_class.message_type] = build_command_proc(command_class)
end

#can_handle?(message) ⇒ Boolean

Does this CommandHandler know how to handle the given command?

Returns:

  • (Boolean)


25
26
27
# File 'lib/pantry/command_handler.rb', line 25

def can_handle?(message)
  !@handlers[message.type].nil?
end

#process(message) ⇒ Object

Given a message, figure out which handler should be triggered and get things rolling



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pantry/command_handler.rb', line 30

def process(message)
  if handler = @handlers[message.type]
    Pantry.logger.debug("[#{@server_or_client.identity}] Running handler on #{message.inspect}")
    handler.call(message)
  else
    Pantry.logger.warn(
      "[#{@server_or_client.identity}] No known handler for message type #{message.type}"
    )
    nil
  end
end