Class: Zero::Router
- Inherits:
-
Object
- Object
- Zero::Router
- Defined in:
- lib/zero/router.rb
Overview
makes it possible to route urls to rack applications
This class can be used to build a small rack application which routes requests to the given application. In the URLs it is also possible to use placeholders which then get assigned as variables to the parameters.
Constant Summary collapse
- VARIABLE_MATCH =
match for variables in routes
%r{:(\w+)[^/]?}
- VARIABLE_REGEX =
the replacement string to make it an regex
'(?<\1>.+?)'
Instance Method Summary collapse
-
#call(env) ⇒ Array
call the router and call the matching application.
-
#initialize(routes) ⇒ Router
constructor
create a new router instance.
Constructor Details
#initialize(routes) ⇒ Router
create a new router instance
34 35 36 37 38 39 40 41 |
# File 'lib/zero/router.rb', line 34 def initialize(routes) @routes = {} routes.each do |route, target| @routes[ Regexp.new( route.gsub(VARIABLE_MATCH, VARIABLE_REGEX) + '$')] = target end end |
Instance Method Details
#call(env) ⇒ Array
call the router and call the matching application
This method has to be called with a rack compatible environment, then the method will find a matching route and call the application.
49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/zero/router.rb', line 49 def call(env) request = Zero::Request.new(env) @routes.each do |route, target| match = route.match(request.path) if match match.names.each_index do |i| request.params[match.names[i]] = match.captures[i] end return target.call(request.env) end end [404, {'Content-Type' => 'text/html'}, ['Not found!']] end |