From 4592817d996f14d226ff667740cd97a660ef0cca Mon Sep 17 00:00:00 2001 From: Jeremy Woertink Date: Wed, 1 Sep 2021 17:03:18 -0700 Subject: [PATCH] Adding new path_without_query_params method. Fixes #1571 --- spec/lucky/action_spec.cr | 22 ++++++++++++++++++++++ src/lucky/routable.cr | 19 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/spec/lucky/action_spec.cr b/spec/lucky/action_spec.cr index 3f56e9ec1..570789f67 100644 --- a/spec/lucky/action_spec.cr +++ b/spec/lucky/action_spec.cr @@ -191,6 +191,28 @@ describe Lucky::Action do end end + describe ".path_without_query_params" do + it "returns path without declared non-nil query params" do + Lucky::RouteHelper.temp_config(base_uri: "example.com") do + RequiredParams::Index.path_without_query_params.should eq "/required_params" + end + end + + it "returns path with (required) path params" do + Lucky::RouteHelper.temp_config(base_uri: "example.com") do + Tests::Edit.path_without_query_params(1).should eq "/tests/1/edit" + end + end + + it "returns path with optional path params" do + Lucky::RouteHelper.temp_config(base_uri: "example.com") do + OptionalRouteParams::Index.path_without_query_params(1).should eq "/complex_posts/1" + OptionalRouteParams::Index.path_without_query_params(1, 2).should eq "/complex_posts/1/2" + OptionalRouteParams::Index.path_without_query_params(1, 2, 3).should eq "/complex_posts/1/2/3" + end + end + end + describe "routing" do it "creates URL helpers for the resourceful actions" do Tests::Index.path.should eq "/tests" diff --git a/src/lucky/routable.cr b/src/lucky/routable.cr index 1336c827a..7fc460dbe 100644 --- a/src/lucky/routable.cr +++ b/src/lucky/routable.cr @@ -267,6 +267,25 @@ module Lucky::Routable Lucky::RouteHelper.new({{ method }}, path).url end + def self.path_without_query_params( + {% for param in path_params %} + {{ param.gsub(/:/, "").id }}, + {% end %} + {% for param in optional_path_params %} + {{ param.gsub(/^\?:/, "").id }} = nil, + {% end %} + ) + path = path_from_parts( + {% for param in path_params %} + {{ param.gsub(/:/, "").id }}, + {% end %} + {% for param in optional_path_params %} + {{ param.gsub(/^\?:/, "").id }}, + {% end %} + ) + Lucky::RouteHelper.new({{ method }}, path).path + end + {% params_with_defaults = PARAM_DECLARATIONS.select do |decl| !decl.value.is_a?(Nop) || decl.type.is_a?(Union) && decl.type.types.last.id == Nil.id end %}