Skip to content

Commit

Permalink
Move the action call body in to a method with a strict return type to…
Browse files Browse the repository at this point in the history
… ensure early returns work and allows Crystal to handle the return type compile errors. Fixes #1843 (#1857)
  • Loading branch information
jwoertink authored Mar 25, 2024
1 parent 3de0f33 commit 74c1ede
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions spec/lucky/action_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,17 @@ class Tests::ComponentActionWithCustomContentType < TestAction
end
end

class Tests::MultiConditionWithEarlyReturn < TestAction
get "/tests/multi_condition_with_early_return" do
data = {check: 1}
if data
return json(data)
end

raw_json("{}")
end
end

describe Lucky::Action do
it "has a url helper" do
Lucky::RouteHelper.temp_config(base_uri: "example.com") do
Expand All @@ -231,6 +242,11 @@ describe Lucky::Action do
end
end

it "allows for early returns" do
response = Tests::MultiConditionWithEarlyReturn.new(build_context, params).call
response.body.to_s.should eq "{\"check\":1}"
end

describe ".url_without_query_params" do
it "returns url without declared non-nil query params" do
Lucky::RouteHelper.temp_config(base_uri: "example.com") do
Expand Down
8 changes: 7 additions & 1 deletion src/lucky/routable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ module Lucky::Routable

# :nodoc:
macro setup_call_method(body)
# Return a response with `html`, `redirect`, or `json` at the end of your action.
# Ensure all conditionals (like if/else) return a response with html, redirect, json, etc.
private def action_call_body : Lucky::Response
{{ body }}
end

def call
# Ensure clients_desired_format is cached by calling it
clients_desired_format
Expand All @@ -96,7 +102,7 @@ module Lucky::Routable
%response = if %pipe_result.is_a?(Lucky::Response)
%pipe_result
else
{{ body }}
action_call_body
end

%pipe_result = run_after_pipes
Expand Down

0 comments on commit 74c1ede

Please sign in to comment.