class Navigable::Router

Constants

DELETE
DYNAMIC_PREFIX
GET
NOT_FOUND_RESPONSE
PATCH
PATH_INFO
POST
PUT
REQUEST_METHOD
ROUTER_PARAMS
VERSION

Public Class Methods

new() click to toggle source
# File lib/navigable/router.rb, line 23
def initialize
  @static = Hash.new { |h, k| h[k] = {} }
  @dynamic = {}
end

Public Instance Methods

call(env) click to toggle source
# File lib/navigable/router.rb, line 49
def call(env)
  endpoint = find_endpoint(env[REQUEST_METHOD], env[PATH_INFO]) { |params| env[ROUTER_PARAMS] = params }
  endpoint ? endpoint.call(env) : NOT_FOUND_RESPONSE
end
delete(path, to:) click to toggle source
# File lib/navigable/router.rb, line 45
def delete(path, to:)
  register_route(DELETE, path, to)
end
get(path, to:) click to toggle source
# File lib/navigable/router.rb, line 28
def get(path, to:)
  register_route(GET, path, to)
  register_route(HEAD, path, to)
end
patch(path, to:) click to toggle source
# File lib/navigable/router.rb, line 41
def patch(path, to:)
  register_route(PATCH, path, to)
end
post(path, to:) click to toggle source
# File lib/navigable/router.rb, line 33
def post(path, to:)
  register_route(POST, path, to)
end
print(stdout = STDOUT) click to toggle source
put(path, to:) click to toggle source
# File lib/navigable/router.rb, line 37
def put(path, to:)
  register_route(PUT, path, to)
end

Private Instance Methods

dynamic(verb) click to toggle source
# File lib/navigable/router.rb, line 80
def dynamic(verb)
  @dynamic[verb] ||= Trie.new
end
dynamic?(path) click to toggle source
# File lib/navigable/router.rb, line 76
def dynamic?(path)
  DYNAMIC_PREFIX.match?(path)
end
find_dynamic(verb, path, &block) click to toggle source
# File lib/navigable/router.rb, line 72
def find_dynamic(verb, path, &block)
  dynamic(verb).find_route(path, &block)
end
find_endpoint(verb, path, &block) click to toggle source
# File lib/navigable/router.rb, line 64
def find_endpoint(verb, path, &block)
  find_static(verb, path, &block) || find_dynamic(verb, path, &block)
end
find_static(verb, path, &block) click to toggle source
# File lib/navigable/router.rb, line 68
def find_static(verb, path, &block)
  @static[verb][path].tap { |endpoint| endpoint && block.call({}) }
end
register_dynamic_route(verb, path, to) click to toggle source
# File lib/navigable/router.rb, line 84
def register_dynamic_route(verb, path, to)
  @dynamic[verb] ||= Trie.new
  @dynamic[verb].add_route(path, to)
end
register_route(verb, path, to) click to toggle source
# File lib/navigable/router.rb, line 60
def register_route(verb, path, to)
  dynamic?(path) ? register_dynamic_route(verb, path, to) : register_static_route(verb, path, to)
end
register_static_route(verb, path, to) click to toggle source
# File lib/navigable/router.rb, line 89
def register_static_route(verb, path, to)
  @static[verb][path] = to
end