Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure actions can have early returns #1857

Merged
merged 1 commit into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading