Skip to content

Commit

Permalink
Improve the generation of the 'exists?' function.
Browse files Browse the repository at this point in the history
  • Loading branch information
RafaelOFreitas committed Jan 24, 2022
1 parent 229e0d5 commit c55a0a3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
8 changes: 5 additions & 3 deletions lib/context_functions_generator.ex
Expand Up @@ -13,9 +13,11 @@ defmodule ContextFunctionsGenerator do
def generate_function(:exists, name, _pluralized_name, module, opts) do
quote do
def unquote(:"#{name}_exists?")(id) do
Ecto.Query.from(m in unquote(module))
|> Ecto.Query.where([m], m.id == ^id)
|> unquote(get_repo_module(opts)).exists?()
import Ecto.Query, only: [from: 2]

query = Ecto.Query.from(x in unquote(module), where: x.id == ^id)

unquote(get_repo_module(opts)).exists?(query)
end
end
end
Expand Down
8 changes: 5 additions & 3 deletions lib/crudry_context.ex
Expand Up @@ -30,9 +30,11 @@ defmodule Crudry.Context do
## Exists functions
def my_schema_exists?(id) do
from(m in MySchema)
|> where([m], m.id == ^id)
|> Repo.exists?()
import Ecto.Query, only: [from: 2]
query = Ecto.Query.from(x in MySchema, where: x.id == ^id)
Repo.exists?(query)
end
## Get functions
Expand Down
2 changes: 0 additions & 2 deletions test/crudry_context_test.exs
Expand Up @@ -2,8 +2,6 @@ defmodule CrudryContextTest do
use ExUnit.Case
doctest Crudry.Context

require Ecto.Query

alias Crudry.Repo
alias Crudry.{Post, User}

Expand Down

0 comments on commit c55a0a3

Please sign in to comment.