Class: FunApi::Router
- Inherits:
-
Object
- Object
- FunApi::Router
- Defined in:
- lib/funapi/router.rb
Defined Under Namespace
Classes: Route
Instance Attribute Summary collapse
-
#routes ⇒ Object
readonly
Returns the value of attribute routes.
Instance Method Summary collapse
- #add(verb, path, metadata: {}, &handler) ⇒ Object
- #call(env) ⇒ Object
-
#initialize ⇒ Router
constructor
A new instance of Router.
Constructor Details
#initialize ⇒ Router
Returns a new instance of Router.
7 8 9 |
# File 'lib/funapi/router.rb', line 7 def initialize @routes = [] end |
Instance Attribute Details
#routes ⇒ Object (readonly)
Returns the value of attribute routes.
11 12 13 |
# File 'lib/funapi/router.rb', line 11 def routes @routes end |
Instance Method Details
#add(verb, path, metadata: {}, &handler) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/funapi/router.rb', line 13 def add(verb, path, metadata: {}, &handler) keys = [] regex = if path == "/" "/" else path.split("/").map do |seg| if seg.start_with?(":") keys << seg.delete_prefix(":") "([^/]+)" else Regexp.escape(seg) end end.join("/") end = .merge(path_template: path) @routes << Route.new(verb.upcase, /\A#{regex}\z/, keys, handler, ) end |
#call(env) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/funapi/router.rb', line 33 def call(env) req = Rack::Request.new(env) route = @routes.find { |r| r.verb == req.request_method && r.pattern =~ req.path_info } return [404, {"content-type" => "application/json"}, [JSON.dump(error: "Not found")]] unless route match = route.pattern.match(req.path_info) params = route.keys.zip(match.captures).to_h route.handler.call(req, params) end |