Class: Spine::Routing::Router

Inherits:
Object
  • Object
show all
Includes:
Syntax::Match, Syntax::Namespacing, Syntax::Verbs
Defined in:
lib/spine/routing/router.rb

Direct Known Subclasses

NestedRouter

Constant Summary collapse

VERB =
'REQUEST_METHOD'.freeze
PATH =
'PATH_INFO'.freeze
PARAMETERS =
'router.parameters'.freeze
NOT_FOUND_RESPONSE =
[404, {}, ['']].freeze

Instance Method Summary collapse

Methods included from Syntax::Namespacing

#scope

Methods included from Syntax::Verbs

#delete, #get, #patch, #post, #put

Methods included from Syntax::Match

#match

Instance Method Details

#add(route) ⇒ Object



31
32
33
# File 'lib/spine/routing/router.rb', line 31

def add(route)
  routes << route
end

#build(pattern, options) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/spine/routing/router.rb', line 18

def build(pattern, options)
  Route.new(
    '',
    normalize_path(pattern),
    options.fetch(:to),
    options.fetch(:verb)
  )
end

#call(env) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/spine/routing/router.rb', line 43

def call(env)
  verb = env[VERB].downcase.gsub('head', 'get').to_sym
  route = recognise(verb, env[PATH])
  if route
    env[PARAMETERS] = Rack::Request.new(env).params
    env[PARAMETERS].merge!(route.parameters)
    run(route.app, env)
  else
    NOT_FOUND_RESPONSE # TODO: set default app
  end
end

#configure(&block) ⇒ Object



27
28
29
# File 'lib/spine/routing/router.rb', line 27

def configure(&block)
  instance_eval &block
end

#recognise(verb, path) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/spine/routing/router.rb', line 35

def recognise(verb, path)
  routes.each do |route|
    match = route.match(verb, path)
    return match if match
  end
  nil
end

#routesObject



14
15
16
# File 'lib/spine/routing/router.rb', line 14

def routes
  @routes ||= [] # TODO: use set instead of array
end

#run(app, env) ⇒ Object



55
56
57
# File 'lib/spine/routing/router.rb', line 55

def run(app, env)
  app.call(env)
end