Created
November 12, 2020 15:17
-
-
Save fuelen/91eed620cd9171031553e12de7a741ef to your computer and use it in GitHub Desktop.
Ecto cond
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Ecto.Extension.Query.API do | |
defmacro cond_(do: block) do | |
bindings = | |
Enum.reduce(block, [], fn | |
{:->, _, [[clause], branch]}, acc -> | |
[branch, clause | acc] | |
end) | |
|> Enum.reverse() | |
bindings_number = length(bindings) | |
sql = | |
[ | |
"CASE", | |
List.duplicate(" WHEN ? THEN ?", div(bindings_number, 2)), | |
" END" | |
] | |
|> IO.iodata_to_binary() | |
quote do | |
fragment(unquote(sql), unquote_splicing(bindings)) | |
end | |
end | |
end | |
defmodule QTest do | |
import Ecto.Extension.Query.API | |
import Ecto.Query | |
def test do | |
from users in "users", | |
select: %{ | |
email: users.email, | |
role_label: | |
cond_ do | |
users.role == "director" -> "DIRECTOR!" | |
true -> type(users.role, :string) | |
end | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment