Class: Wouter
- Inherits:
-
Object
- Object
- Wouter
- Defined in:
- lib/wouter.rb
Defined Under Namespace
Classes: Endpoint, Request, Response
Constant Summary collapse
- @@routes =
Route Definitions
[]
Class Method Summary collapse
-
.call(env) ⇒ Object
Rack API.
-
.generate_params(params) ⇒ Object
Query string comes in as “key=value&key=value” and we turn it into { “key” => “value”, “key” => “value” }.
-
.not_found ⇒ Object
Helpers.
- .response(route_response) ⇒ Object
Class Method Details
.call(env) ⇒ Object
Rack API
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/wouter.rb', line 90 def self.call(env) path = env["PATH_INFO"] method = env["REQUEST_METHOD"].to_sym route_params = {} route = @@routes.find do |route| if route[:method] == method if route[:path].include?(":") split_path = route[:path].split("/") # Find all the named parameters in the route, drop the ":" so we have the names: ":id" => "id" route_param_names = split_path.find_all { |s| s.size > 1 ? s[0] == ":" : false }.map { |s| s[1..-1] } # Turn the route into a regex: "/hello/:name" => "\/hello\/(\w*)" path_regex_string = split_path.map { |s| s[0] == ":" ? "(\\w*)" : s }.join("\/") r = Regexp.new(path_regex_string) if r.match?(path) match_data = r.match(path) # Match the match data with the named params, ex { "id" => 123 } route_param_names.each_with_index do |n, i| route_params[n] = match_data[i+1] end true else false end else route[:path] == path end end end if route params = generate_params(env["rack.input"].gets).merge(route_params) request = Request.new(params: params) response = Response.new route_response = route[:route_class].new.call(request, response) response route_response else response not_found end end |
.generate_params(params) ⇒ Object
Query string comes in as “key=value&key=value” and we turn it into { “key” => “value”, “key” => “value” }
143 144 145 146 147 148 149 150 151 |
# File 'lib/wouter.rb', line 143 def self.generate_params(params) return {} if params.nil? || params.empty? params_hash = {} params.split("&").each do |param_pair| key, value = param_pair.split("=") params_hash[key] = value end params_hash end |
.not_found ⇒ Object
Helpers
136 137 138 139 140 |
# File 'lib/wouter.rb', line 136 def self.not_found resp = Response.new resp.status 404 resp.body "Not Found" end |
.response(route_response) ⇒ Object
153 154 155 |
# File 'lib/wouter.rb', line 153 def self.response(route_response) route_response.build_response end |