lib/on_irc/server.rb in on_irc-2.0.0 vs lib/on_irc/server.rb in on_irc-2.0.1
- old
+ new
@@ -1,41 +1,53 @@
-module IRC
+class IRC
class Server
- attr_accessor :config, :connection, :handlers
+ attr_accessor :config, :connection, :handlers, :name, :irc
config_accessor :address, :port, :nick, :ident, :realname, :ssl
-
- def initialize(config)
+
+ def initialize(irc, name, config)
+ @irc = irc
+ @name = name
@config = config
@handlers = {}
end
-
+
+ def send_cmd(cmd, *args)
+ # prepend last arg with : only if it exists. it's really ugly
+ args[-1] = ":#{args[-1]}" if args[-1]
+ connection.send_data(cmd.to_s.upcase + ' ' + args.join(' ') + "\r\n")
+ end
+
def on(event, &block)
@handlers[event.to_s.downcase.to_sym] = Callback.new(block)
end
-
- Config = Struct.new(:address, :port, :nick, :ident, :realname, :ssl)
-
- class ConfigDSL
- dsl_accessor :address, :port, :nick, :ident, :realname
- bool_dsl_accessor :ssl
-
- def self.run(&block)
- confdsl = self.new
- block.arity < 1 ? confdsl.instance_eval(&block) : block.call(confdsl)
-
- raise ConfigError, 'no address' unless confdsl.address
-
- conf = Config.new
-
- conf.address = confdsl.address
- # If not supplied, the port defaults to 6667, or 6697 if ssl is used
- conf.port = confdsl.port || (confdsl.ssl? ? 6697 : 6667)
- conf.ssl = confdsl.ssl?
- conf.nick = confdsl.nick
- conf.ident = confdsl.ident
- conf.realname = confdsl.realname
-
- conf
+
+ def handle_event(event)
+ if @handlers[:all]
+ @handlers[:all].call(@irc, event)
+ elsif @irc.handlers[:all]
+ @irc.handlers[:all].call(@irc, event)
+ end
+
+ if @handlers[event.command]
+ @handlers[event.command].call(@irc, event)
+ elsif @irc.handlers[event.command]
+ @irc.handlers[event.command].call(@irc, event)
+ end
+ end
+
+ # Eventmachine callbacks
+ def receive_line(line)
+ parsed_line = Parser.parse(line)
+ event = Event.new(self, parsed_line[:prefix],
+ parsed_line[:command].downcase.to_sym,
+ parsed_line[:params])
+ handle_event(event)
+ end
+
+ def unbind
+ EM.add_timer(3) do
+ connection.reconnect(config.address, config.port)
+ connection.post_init
end
end
end
end