PhoenixBricks.Scopes (phoenix_bricks v0.2.0) View Source

Defines a common interface for adding scopes to a Schema

Examples

defmodule RecordQuery do
  use ExBricks.Scopes, schema: Record
end

It provides you a method scope that improve the empty scope of provided schema with additional scopes.

scope/0 returns the empty scope

iex> RecordQuery.scope()
iex> Record

With scope/1 you can provide a list of scopes that improve the starting scope

iex> scopes = [field1: {:eq, "value"}, field2: {:gte, 42}]
iex> RecordQuery.scope(scopes)
iex> #Ecto.Query<from r0 in Record, where: r0.field1 == ^"value" and r0.field2 >= 42>

If you need to improve an existing Ecto.Query you can use scope/2

iex> starting_scope = from(r in Record, where: r.field1 == "value")
iex> scopes = [field2: {:gte, 42}]
iex> RecordQuery.scope(starting_scope, scopes)
iex> #Ecto.Query<from r0 in Record, where: r0.field1 == ^"value" and r0.field2 >= 42>

Built-in scopes

:eq

iex> RecordQuery.scope(field: {:eq, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields == ^"value">

:gt

iex> RecordQuery.scope(field: {:gt, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields > ^"value">

:lt

iex> RecordQuery.scope(field: {:lt, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields < ^"value">

:gte

iex> RecordQuery.scope(field: {:gte, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields >= ^"value">

:lte

iex> RecordQuery.scope(field: {:lte, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields <= ^"value">

:neq

iex> RecordQuery.scope(field: {:neq, "value"})
iex> #Ecto.Query<from r0 in Record, where: r0.fields != ^"value">

:matches

iex> RecordQuery.scope(field: {:matches, "value"})
iex> #Ecto.Query<from r0 in Record, where: ilike(r0.field, ^"%value%")>

Customize scopes

If you need to define more comprehensive scopes you can improve the query adding new apply_scope/2 methods

defmodule RecordQuery, do
  use ExBricks.Scopes, schema: Record

  defp apply_scope(query, {:name_matches, "value"}) do
    query
    |> apply_scope(:name, {:matches, "value"})
  end

  defp apply_scope(query, {:published}) do
    query
    |> where([p], p.status == "published")
  end
end

iex> RecordQuery.scope(:published, name_matches: "value")
iex> #Ecto.Query<from r0 in Record, where: r0.status == "published" and ilike(r0.name, ^"%value%")>