Specifying a String Value in a Type Definition for Elixir Type Types

Is it possible to determine the type as follows:

defmodule Role do
  use Exnumerator, values: ["admin", "regular", "restricted"]

  @type t :: "admin" | "regular" | "restricted"

  @spec default() :: t
  def default() do
    "regular"
  end
end

to better analyze the code:

@type valid_attributes :: %{optional(:email) => String.t,
                            optional(:password) => String.t,
                            optional(:role) => Role.t}

@spec changeset(User.t, valid_attributes) :: Ecto.Changeset.t
def changeset(%User{} = user, attrs = %{}) do
  # ...
end

# ...

User.changeset(%User{}, %{role: "superadmin"}) |> Repo.insert()

I know that I can define this type as @type t :: String.t, but then Dialyzer will not complain about using a different value than is possible (possibly from the point of view of the application).

I have not seen any hints of this use case in the documentation for Typespecs , but maybe I am missing something.

+4
source share
1 answer

. - - Ecto:

defmodule Role do
  @behaviour Ecto.Type

  @type t :: :admin | :regular | :restricted
  @valid_binary_values ["admin", "regular", "restricter"]

  @spec default() :: t
  def default(), do: :regular

  @spec valid_values() :: list(t)
  def valid_values(), do: Enum.map(@valid_values, &String.to_existing_atom/1)

  @spec type() :: atom()
  def type(), do: :string

  @spec cast(term()) :: {:ok, atom()} | :error
  def cast(value) when is_atom(value), do: {:ok, value}
  def cast(value) when value in @valid_binary_values, do: {:ok, String.to_existing_atom(value)}
  def cast(_value), do: :error

  @spec load(String.t) :: {:ok, atom()}
  def load(value), do: {:ok, String.to_existing_atom(value)}

  @spec dump(term()) :: {:ok, String.t} | :error
  def dump(value) when is_atom(value), do: {:ok, Atom.to_string(value)}
  def dump(_), do: :error
end

:

defmodule User do
  use Ecto.Schema

  import Ecto.Changeset

  @type t :: %User{}
  @type valid_attributes :: %{optional(:email) => String.t,
                              optional(:password) => String.t,
                              optional(:role) => Role.t}

  @derive {Poison.Encoder, only: [:email, :id, :role]}
  schema "users" do
    field :email, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :role, Role, default: Role.default()

    timestamps()
  end

  @spec changeset(User.t, valid_attributes) :: Ecto.Changeset.t
  def changeset(%User{} = user \\ %User{}, attrs = %{}) do
  # ...
end

, Dialyzer :

User.changeset(%User{}, %{role: :superadmin}) |> Repo.insert()

, . , ( , ).

+5

Source: https://habr.com/ru/post/1689332/


All Articles