Class: ActionJabber::Server
- Inherits:
-
Object
- Object
- ActionJabber::Server
- Defined in:
- lib/actionjabber.rb
Defined Under Namespace
Classes: Request
Instance Method Summary collapse
-
#initialize(username, password, controller, debug = false) ⇒ Server
constructor
Sets up the server.
-
#respond_to(request, opts = {}) ⇒ Object
Handles actually sending response data to the client.
-
#run!(frequency = 0) ⇒ Object
Initiates the loop to check for new messages.
Constructor Details
#initialize(username, password, controller, debug = false) ⇒ Server
Sets up the server. The controller
argument is expected to be a class, not an instance.
28 29 30 31 32 |
# File 'lib/actionjabber.rb', line 28 def initialize(username, password, controller, debug = false) @jabber = Jabber::Simple.new(username, password) @controller = controller # Should be a class. @debug = debug end |
Instance Method Details
#respond_to(request, opts = {}) ⇒ Object
Handles actually sending response data to the client.
74 75 76 77 78 79 80 81 82 83 |
# File 'lib/actionjabber.rb', line 74 def respond_to(request, opts = {}) from = request.from status = opts[:status] or 200 data = opts[:data] or '' resp = "#{request.hash}:#{opts[:status]}" unless data.to_s.empty? resp += (':' + data.to_s) end @jabber.deliver(Jabber::JID.new(request.from), resp) end |
#run!(frequency = 0) ⇒ Object
Initiates the loop to check for new messages.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/actionjabber.rb', line 34 def run!(frequency = 0) while @jabber.connected? @jabber. do || start = Time.now from = .from.to_s.split('/').first parts = .body.strip.split(':', 2) hash = parts.first path_parts = parts.last.split('?', 2) request = Request.new(hash, from, path_parts.first, ((path_parts.length == 2) ? path_parts.last : '')) # TODO: DRY this portion up. if @debug # Allow errors to fall through and kill the process. controller_response = @controller.route!(request) response = {:status => 200, :data => ''}.merge(controller_response) respond_to request, :status => response[:status], :data => response[:data] puts "Responded to '#{from}' in #{(Time.now - start).to_s} seconds." else # Capture the errors so that the server keeps on running. begin controller_response = @controller.route!(request) response = {:status => 200, :data => ''}.merge(controller_response) respond_to request, :status => response[:status], :data => response[:data] rescue respond_to request, :status => 500 puts "Error responding to #{.from.to_s.strip}:" puts $! else puts "Responded to '#{from}' in #{(Time.now - start).to_s} seconds." end end #puts "\n" end if frequency > 0 # Keep it from hogging up CPU cycles. sleep frequency end end end |