Class: Hyraft::Router::ApiRouter

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

Defined Under Namespace

Classes: Route

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeApiRouter

Returns a new instance of ApiRouter.



7
8
9
# File 'lib/hyraft/router/api_router.rb', line 7

def initialize
  @routes = []
end

Class Method Details

.draw(&block) ⇒ Object



11
12
13
14
15
# File 'lib/hyraft/router/api_router.rb', line 11

def self.draw(&block)
  router = new
  router.instance_eval(&block)
  router
end

Instance Method Details

#add_route(http_method, path, to) ⇒ Object



52
53
54
55
56
# File 'lib/hyraft/router/api_router.rb', line 52

def add_route(http_method, path, to)
  handler_class, action_name = to
  regex = compile(path)
  @routes << Route.new(http_method, path, handler_class, action_name, regex)
end

#DELETE(path, to:) ⇒ Object



29
30
31
# File 'lib/hyraft/router/api_router.rb', line 29

def DELETE(path, to:)
  add_route('DELETE', path, to)
end

#GET(path, to:) ⇒ Object



17
18
19
# File 'lib/hyraft/router/api_router.rb', line 17

def GET(path, to:)
  add_route('GET', path, to)
end

#POST(path, to:) ⇒ Object



21
22
23
# File 'lib/hyraft/router/api_router.rb', line 21

def POST(path, to:)
  add_route('POST', path, to)
end

#PUT(path, to:) ⇒ Object



25
26
27
# File 'lib/hyraft/router/api_router.rb', line 25

def PUT(path, to:)
  add_route('PUT', path, to)
end

#resolve(http_method, path_info) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hyraft/router/api_router.rb', line 33

def resolve(http_method, path_info)
  path = path_info.split('?').first
  
  # Try exact matches first
  exact_match = @routes.find do |r| 
    r.http_method == http_method && r.path == path
  end
  return [exact_match, []] if exact_match
  
  # Then try regex matches
  @routes.each do |r|
    if r.http_method == http_method && (match = r.regex.match(path))
      return [r, match.captures]
    end
  end
  
  nil
end