Skip to content

Commit

Permalink
improvement: handle when clauses on anonymous functions
Browse files Browse the repository at this point in the history
  • Loading branch information
zachdaniel committed Aug 17, 2023
1 parent f997db9 commit 0e578bb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
22 changes: 17 additions & 5 deletions lib/spark/code_helpers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,23 @@ defmodule Spark.CodeHelpers do
function = generate_captured_function_caller(fn_name, fn_args, caller)

function_defs =
for {:->, _, [args, body]} <- clauses do
quote do
def unquote(fn_name)(unquote_splicing(args)) do
unquote(body)
end
for clause <- clauses do
case clause do
{:->, _, [[{:when, _, args_with_clause}], body]} ->
args = :lists.droplast(args_with_clause)
clause = List.last(args_with_clause)
quote do
def unquote(fn_name)(unquote_splicing(args)) when unquote(clause) do
unquote(body)
end
end

{:->, _, [args, body]} ->
quote do
def unquote(fn_name)(unquote_splicing(args)) do
unquote(body)
end
end
end
end

Expand Down
2 changes: 1 addition & 1 deletion test/dsl_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ defmodule Spark.DslTest do
use Spark.Test.Contact

contact do
contacter(fn message ->
contacter(fn message when not is_nil(message) ->
"Help me Obi-Wan Kenobi: #{message}"
end)
end
Expand Down

0 comments on commit 0e578bb

Please sign in to comment.