diff --git a/spec/fragment_spec.cr b/spec/fragment_spec.cr index 096b2b6..39244a2 100644 --- a/spec/fragment_spec.cr +++ b/spec/fragment_spec.cr @@ -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) diff --git a/src/lucky_router/fragment.cr b/src/lucky_router/fragment.cr index 671341f..838f065 100644 --- a/src/lucky_router/fragment.cr +++ b/src/lucky_router/fragment.cr @@ -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 diff --git a/src/lucky_router/matcher.cr b/src/lucky_router/matcher.cr index 7b51b96..2342789 100644 --- a/src/lucky_router/matcher.cr +++ b/src/lucky_router/matcher.cr @@ -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)