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

Add multipart convenience argument to form_for helper. #1200

Merged
merged 1 commit into from Jun 22, 2020
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
24 changes: 24 additions & 0 deletions spec/lucky/form_helpers_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ private class TestPage
text "foo"
end
end

def form_with_multipart
form_for FormHelpers::Create, multipart: true do
text "foo"
end
end

def form_with_multipart_false
form_for FormHelpers::Create, multipart: false do
text "foo"
end
end
end

describe Lucky::FormHelpers do
Expand Down Expand Up @@ -86,6 +98,18 @@ describe Lucky::FormHelpers do
<form action="/form_helpers" method="get"><input type="hidden" name="#{Lucky::ProtectFromForgery::PARAM_KEY}" value="my_token"></form>
HTML
end

it "converts the multipart argument" do
without_csrf_protection do
view(&.form_with_multipart).should contain <<-HTML
<form action="/form_helpers" method="post" enctype="multipart/form-data">foo</form>
HTML

view(&.form_with_multipart_false).should contain <<-HTML
<form action="/form_helpers" method="post">foo</form>
HTML
end
end
end

private def without_csrf_protection
Expand Down
13 changes: 11 additions & 2 deletions src/lucky/tags/form_helpers.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ module Lucky::FormHelpers
end

def form_for(route : Lucky::RouteHelper, **html_options) : Nil
form_options = {"action" => route.path, "method" => form_method(route)}
form merge_options(html_options, form_options) do
form build_form_options(route, html_options) do
csrf_hidden_input if settings.include_csrf_tag
method_override_input(route)
yield
Expand All @@ -24,6 +23,16 @@ module Lucky::FormHelpers
end
end

private def build_form_options(route, html_options) : Hash
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love the abstraction!

options = merge_options(html_options, {
"action" => route.path,
"method" => form_method(route),
})
options["enctype"] = "multipart/form-data" if options.delete("multipart")

options
end

private def method_override_input(route) : Nil
unless [:post, :get].includes? route.method
input type: "hidden", name: "_method", value: route.method.to_s
Expand Down