Class: RubyAPI::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyapi/router.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



5
6
7
8
9
# File 'lib/rubyapi/router.rb', line 5

def initialize
  @routes = []
  @trie = TrieNode.new
  @current_prefix = ""
end

Instance Attribute Details

#current_prefixObject (readonly)

Returns the value of attribute current_prefix.



3
4
5
# File 'lib/rubyapi/router.rb', line 3

def current_prefix
  @current_prefix
end

#routesObject (readonly)

Returns the value of attribute routes.



3
4
5
# File 'lib/rubyapi/router.rb', line 3

def routes
  @routes
end

Instance Method Details

#add_route(method, path, **opts, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rubyapi/router.rb', line 11

def add_route(method, path, **opts, &block)
  full_path = @current_prefix + path
  pattern = compile_pattern(full_path)
  param_names = extract_param_names(full_path)

  route = {
    method: method,
    path: full_path,
    pattern: pattern,
    param_names: param_names,
    block: block,
    params: opts[:params] || {},
    body: opts[:body],
    injected_deps: opts[:inject] || [],
    dependency_checks: opts[:depends] || []
  }

  @routes << route
  @trie.insert(full_path, route)
  route
end

#find(method, path) ⇒ Object



41
42
43
44
45
46
# File 'lib/rubyapi/router.rb', line 41

def find(method, path)
  route = @trie.search(path)
  return nil unless route
  return nil unless route[:method].to_s == method.to_s
  route
end

#pop_prefix(prefix) ⇒ Object



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

def pop_prefix(prefix)
  @current_prefix = @current_prefix[0...-prefix.length]
end

#push_prefix(prefix) ⇒ Object



33
34
35
# File 'lib/rubyapi/router.rb', line 33

def push_prefix(prefix)
  @current_prefix = @current_prefix + prefix
end