Class: Rain::Router

Inherits:
Object
  • Object
show all
Includes:
LowType, Observers
Defined in:
lib/router/router.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



17
18
19
20
21
# File 'lib/router/router.rb', line 17

def initialize
  @breadcrumbs = []
  @routes = {}
  @trie = Trie.new
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



15
16
17
# File 'lib/router/router.rb', line 15

def routes
  @routes
end

#trieObject (readonly)

Returns the value of attribute trie.



15
16
17
# File 'lib/router/router.rb', line 15

def trie
  @trie
end

Instance Method Details

#delete(path, &block) ⇒ Object



48
49
50
# File 'lib/router/router.rb', line 48

def delete(path, &block)
  route(path, 'DELETE', &block)
end

#get(path, &block) ⇒ Object



36
37
38
# File 'lib/router/router.rb', line 36

def get(path, &block)
  route(path, 'GET', &block)
end

#handle(event:) ⇒ Object

TODO: Define type: ::Low::Events::RequestEvent You can override any route/status simply by adding your own observer.



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/router/router.rb', line 54

def handle(event:)
  response_event = nil

  # The last route event will render a response event which we want to return to the request event.
  @trie.match(path: event.request.path.delete_suffix('/')).each do |route_event|
    response_event = route_event.trigger
  end

  return response_event if response_event

  Low::Events::StatusEvent.trigger(status: Low::Types::Status[404], request: event.request)
end

#post(path, &block) ⇒ Object



40
41
42
# File 'lib/router/router.rb', line 40

def post(path, &block)
  route(path, 'POST', &block)
end

#route(path, verbs = [], &block) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/router/router.rb', line 23

def route(path, verbs = [], &block)
  @breadcrumbs << path
  path = @breadcrumbs.join

  route = Route.new(path:, verbs: [*verbs])
  @routes[path] = route
  @trie.merge(route:)

  block.call if block_given?

  @breadcrumbs.pop
end

#update(path, &block) ⇒ Object



44
45
46
# File 'lib/router/router.rb', line 44

def update(path, &block)
  route(path, 'UPDATE', &block)
end