Created
March 19, 2010 17:47
-
-
Save raws/337951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Wheaties | |
class Connection < EventMachine::Protocols::LineAndTextProtocol | |
attr_reader :nick, :user, :real, :channels | |
class << self | |
def instance | |
@@instance | |
end | |
end | |
def initialize | |
@@instance = self | |
@nick = Wheaties.config["nick"] | |
@user = Wheaties.config["user"] | |
@real = Wheaties.config["real"] | |
@channels = Set.new | |
super | |
end | |
def post_init | |
log(:info, "Connection opened") | |
Signal.trap("INT") do | |
close_connection_after_writing | |
EM.stop_event_loop | |
end | |
set_comm_inactivity_timeout((Wheaties.config["timeout"] || 300).to_i) | |
identify | |
end | |
def identify | |
pass = Wheaties.config["pass"] | |
broadcast("PASS", pass) if pass | |
broadcast("NICK", nick) | |
broadcast("USER", user, "0", "*", :text => real) | |
end | |
def receive_line(line) | |
operator = Proc.new do | |
begin | |
response = Response.new(line) | |
log(:debug, "<--", response.to_s.inspect) | |
Handler.new(response).handle | |
rescue => e | |
log(:error, e.message, e.backtrace) | |
end | |
end | |
callback = Proc.new do |result| | |
instance_eval(&result) if result.is_a?(Proc) | |
end | |
EM.defer(operator, callback) | |
end | |
def unbind | |
if error? | |
log(:info, "Connection timed out. Reconnecting...") | |
Wheaties.connect | |
else | |
log(:info, "Connection closed") | |
EM.stop_event_loop | |
end | |
end | |
def broadcast(command, *args) | |
@sender ||= EventMachine.spawn do |command, *args| | |
connection = Connection.instance | |
request = Request.new(command, *args) | |
connection.send_data(request.to_s) | |
connection.log(:debug, "-->", request.to_s.inspect) unless request.sensitive? | |
end.notify(command, *args) | |
end | |
def log(level, *args) | |
Wheaties.logger.send(level, args.join(" ")) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment