Skip to content

Commit

Permalink
Adds ability to list routes for lucky routes command
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmcgarvey committed Jun 12, 2024
1 parent d4e8fc7 commit 27abbc3
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions spec/fragment_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ describe LuckyRouter::Fragment do
id_fragment.static_parts["edit"].should_not be_nil
id_fragment.static_parts["new"].should_not be_nil
end

describe "#collect_routes" do
it "returns list of routes from fragment" do
fragment = build_fragment
fragment.process_parts(build_path_parts("users", ":id"), "get", :show)

result = fragment.collect_routes

result.size.should eq(1)
result[0].should eq({
[LuckyRouter::PathPart.new(""), LuckyRouter::PathPart.new("users"), LuckyRouter::PathPart.new(":id")],
"get",
:show,
})
end
end
end

private def build_path_parts(*path_parts) : Array(LuckyRouter::PathPart)
Expand Down
23 changes: 23 additions & 0 deletions src/lucky_router/fragment.cr
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,29 @@ class LuckyRouter::Fragment(T)
def initialize(@path_part)
end

def collect_routes : Array(Tuple(Array(PathPart), String, T))
routes = [] of Tuple(Array(PathPart), String, T)
method_to_payload.each do |method, payload|
routes << {[path_part], method, payload}
end

routes += dynamic_parts.flat_map(&.collect_routes).map do |item|
item[0].unshift(path_part)
item
end
routes += static_parts.values.flat_map(&.collect_routes).map do |item|
item[0].unshift(path_part)
item
end
if gp = glob_part
routes += gp.collect_routes.map do |item|
item[0].unshift(path_part)
item
end
end
routes
end

# This looks for a matching fragment for the given parts
# and returns NoMatch if one is not found
def find(parts : Array(String), method : String) : Match(T) | NoMatch
Expand Down
8 changes: 8 additions & 0 deletions src/lucky_router/matcher.cr
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ class LuckyRouter::Matcher(T)
end
end

# Array of the path, method, and payload
def list_routes : Array(Tuple(String, String, T))
root.collect_routes.map do |(path_parts, method, payload)|
path = "/" + path_parts.reject(&.part.presence.nil?).map(&.part).join("/")
Tuple.new(path, method, payload)
end
end

private def process_and_add_path(method : String, parts : Array(PathPart), payload : T, path : String)
if method.downcase == "get"
root.process_parts(parts, "head", payload)
Expand Down

0 comments on commit 27abbc3

Please sign in to comment.