Class: Mayu::Routing::Matcher

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mayu/routing/matcher.rb

Defined Under Namespace

Classes: RouteError

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Matcher

Returns a new instance of Matcher.



13
14
15
# File 'lib/mayu/routing/matcher.rb', line 13

def initialize(root)
  @root = root
end

Instance Method Details

#match(path) ⇒ Object

Raises:



18
19
20
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
46
47
48
49
50
51
52
53
54
55
# File 'lib/mayu/routing/matcher.rb', line 18

def match(path)
  layouts = []
  parts = []
  params = {}

  not_found = T.let(nil, T.nilable(String))

  found =
    path
      .delete_prefix("/")
      .split("/")
      .reduce(@root) do |curr, part|
        layouts.push(File.join("", *parts, curr.layout)) if curr.layout

        if curr.not_found
          not_found = File.join("", *parts, curr.not_found)
        end

        match = curr.match(part)

        break unless match

        if match.is_a?(Routes::Param)
          params[match.name.to_sym] = part
          parts.push(":#{part}")
        else
          parts.push(part)
        end

        match
      end

  return { layouts:, component: File.join("", *parts), params: } if found

  return { layouts: [], component: not_found, params: } if not_found

  raise RouteError, "No 404 page configured, put one in #{@root}"
end