summaryrefslogtreecommitdiff
path: root/lib/nickserver/dispatcher.rb
diff options
context:
space:
mode:
authorAzul <azul@riseup.net>2016-08-29 10:26:54 +0200
committerAzul <azul@riseup.net>2016-08-29 10:34:17 +0200
commitbecd26b0bdf44b3625caaa7643914d0379a4fea5 (patch)
tree8f6e5ddf548ce9262a7cabac76ed2f4e3873be22 /lib/nickserver/dispatcher.rb
parent58d687f927aabc8aa2fdfc46132cb71706bdde46 (diff)
refactor: let handlers check if they are applicable
Instead of testing the preconditions for each handler in the dispatcher the dispatcher hands a request to one handler after the other until one of them responds. This is similar to the Chain of Responsibility patter but we iterate over the 'handler_chain' array instead of a linked list. To change the order of handlers or add other handlers change the array in the handler_chain function.
Diffstat (limited to 'lib/nickserver/dispatcher.rb')
-rw-r--r--lib/nickserver/dispatcher.rb33
1 files changed, 24 insertions, 9 deletions
diff --git a/lib/nickserver/dispatcher.rb b/lib/nickserver/dispatcher.rb
index b818b98..833a2ad 100644
--- a/lib/nickserver/dispatcher.rb
+++ b/lib/nickserver/dispatcher.rb
@@ -1,3 +1,18 @@
+#
+# Dispatcher
+#
+# Dispatch a request so it get's handled by the correct handler.
+#
+# The dispatcher hands a request to one handler after the other until one of
+# them responds.
+#
+# This is similar to the Chain of Responsibility patter but we iterate over the
+# 'handler_chain' array instead of a linked list.
+#
+# To change the order of handlers or add other handlers change the array in the
+# handler_chain function.
+#
+
require 'nickserver/request'
require 'nickserver/request_handlers/email_handler'
require 'nickserver/request_handlers/fingerprint_handler'
@@ -18,22 +33,22 @@ module Nickserver
protected
def handle(request)
- handler = handler_for_request request
- handler.call request
+ handler_chain.each do |handler|
+ response = handler.call request
+ return response if response
+ end
rescue RuntimeError => exc
puts "Error: #{exc}"
puts exc.backtrace
ErrorResponse.new(exc.to_s)
end
- def handler_for_request(request)
- if request.email
- RequestHandlers::EmailHandler.new
- elsif request.fingerprint
- RequestHandlers::FingerprintHandler.new
- else
+ def handler_chain
+ [
+ RequestHandlers::EmailHandler.new,
+ RequestHandlers::FingerprintHandler.new,
Proc.new { Nickserver::Response.new(404, "Not Found\n") }
- end
+ ]
end
def send_response(status = 200, content = '')