class Webmachine::Dispatcher
Handles dispatching incoming requests to the proper registered resources and initializing the decision logic.
Constants
- WM_DISPATCH
Attributes
The creator for resources used to process requests. Must respond to call(route, request, response) and return a newly created resource instance.
Public Class Methods
Initialize a Dispatcher
instance @param resource_creator
Invoked to create resource instances.
# File lib/webmachine/dispatcher.rb, line 23 def initialize(resource_creator = method(:create_resource)) @routes = [] @resource_creator = resource_creator end
Public Instance Methods
Adds a route to the dispatch list. Routes will be matched in the order they are added. @see Route#new
# File lib/webmachine/dispatcher.rb, line 31 def add_route(*args, &block) route = Route.new(*args, &block) @routes << route route end
Dispatches a request to the appropriate {Resource} in the dispatch list. If a matching resource is not found, a “404 Not Found” will be rendered. @param [Request] request the request object @param [Response] response the response object
# File lib/webmachine/dispatcher.rb, line 43 def dispatch(request, response) if resource = find_resource(request, response) Webmachine::Events.instrument(WM_DISPATCH) do |payload| Webmachine::Decision::FSM.new(resource, request, response).run payload[:resource] = resource.class.name payload[:request] = request.dup payload[:code] = response.code end else Webmachine.render_error(404, request, response) end end
Find the first resource that matches an incoming request @param [Request] request the request to match @param [Response] response the response for the resource
# File lib/webmachine/dispatcher.rb, line 66 def find_resource(request, response) if route = find_route(request) prepare_resource(route, request, response) end end
Find the first route that matches an incoming request @param [Request] request the request to match
# File lib/webmachine/dispatcher.rb, line 74 def find_route(request) @routes.find { |r| r.match?(request) } end
Resets, removing all routes. Useful for testing or reloading the application.
# File lib/webmachine/dispatcher.rb, line 59 def reset @routes.clear end
Private Instance Methods
# File lib/webmachine/dispatcher.rb, line 85 def create_resource(route, request, response) route.resource.new(request, response) end
# File lib/webmachine/dispatcher.rb, line 80 def prepare_resource(route, request, response) route.apply(request) @resource_creator.call(route, request, response) end