Class: Takagi::Router

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

Direct Known Subclasses

Base

Constant Summary collapse

@@routes =
{}

Class Method Summary collapse

Class Method Details

.find_route(method, path) ⇒ Object



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

def self.find_route(method, path)
  return @@routes["#{method} #{path}"], {} if @@routes.key?("#{method} #{path}")

  match_dynamic_route(method, path)
end

.get(path, &block) ⇒ Object



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

def self.get(path, &block)
  @@routes["GET #{path}"] = block
end

.match_dynamic_route(method, path) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/takagi/router.rb', line 21

def self.match_dynamic_route(method, path)
  @@routes.each do |route_key, block|
    route_method, route_path = route_key.split(" ", 2)
    next unless route_method == method

    route_parts = route_path.split("/")
    path_parts = path.split("/")
    next unless route_parts.length == path_parts.length

    params = {}
    match = route_parts.each_with_index.all? do |part, index|
      if part.start_with?(":")
        param_name = part[1..]
        params[param_name.to_sym] = path_parts[index]
        true
      else
        part == path_parts[index]
      end
    end

    return [block, params] if match
  end

  [nil, {}]
end

.post(path, &block) ⇒ Object



11
12
13
# File 'lib/takagi/router.rb', line 11

def self.post(path, &block)
  @@routes["POST #{path}"] = block
end