Skip to content

Instantly share code, notes, and snippets.

@fuelen
Created November 12, 2020 15:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuelen/91eed620cd9171031553e12de7a741ef to your computer and use it in GitHub Desktop.
Save fuelen/91eed620cd9171031553e12de7a741ef to your computer and use it in GitHub Desktop.
Ecto cond
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