Skip to content
Browse files

Refactor the command processing to use simple handler blocks

  • Loading branch information...
1 parent 68709ba commit 3d47a5138d72e0b68610b2aa45acab3fe9ec7969 @halorgium halorgium committed Dec 12, 2007
Showing with 34 additions and 4 deletions.
  1. +34 −4 lib/bot/client.rb
View
38 lib/bot/client.rb
@@ -8,6 +8,7 @@ module Bot
class Client
def initialize(hostname, port, nick, user, full_name)
@hostname, @port, @nick, @user, @full_name = hostname, port, nick, user, full_name
+ setup_handlers
end
attr_reader :hostname, :port, :nick, :user, :full_name
attr_accessor :connection
@@ -44,12 +45,41 @@ def dispatch(line)
end
def process(command)
- case command
- when Irc::Commands::Ping
- command.respond_with("PONG", command.server1, command.server2)
+ set = handlers[command.class]
+ if set.empty?
+ puts "No handlers for #{command.inspect}"
else
- puts "Unable to process #{command.inspect}"
+ set.each do |handler|
+ handler.call(command)
+ end
+ end
+ end
+
+ def setup_handlers
+ add_command_handler(:Ping) do |command|
+ command.respond_with("PONG", command.server1, command.server2)
+ end
+ end
+
+ def handlers
+ @handlers ||= Hash.new do |h,k|
+ h[k] = []
end
end
+
+ def add_handler(const, block)
+ handlers[const] ||= []
+ handlers[const] << block
+ end
+
+ def add_numeric_handler(name, &block)
+ const = Irc::Commands::Numeric.const_get(name)
+ add_handler(const, block)
+ end
+
+ def add_command_handler(name, &block)
+ const = Irc::Commands.const_get(name)
+ add_handler(const, block)
+ end
end
end

0 comments on commit 3d47a51

Please sign in to comment.
Something went wrong with that request. Please try again.