View Source Ash.Type.Enum behaviour (ash v2.21.4)

A type for abstracting enums into a single type.

For example, your existing attribute might look like:

attribute :status, :atom, constraints: [one_of: [:open, :closed]]

But as that starts to spread around your system, you may find that you want to centralize that logic. To do that, use this module to define an Ash type easily:

defmodule MyApp.TicketStatus do
  use Ash.Type.Enum, values: [:open, :closed]
end

Then, you can rewrite your original attribute as follows:

attribute :status, MyApp.TicketStatus

Valid values are:

  • The atom itself, e.g :open
  • A string that matches the atom, e.g "open"
  • A string that matches the atom after being downcased, e.g "OPEN" or "oPeN"
  • A string that matches the stringified, downcased atom, after itself being downcased. This allows for enum values like :Open, :SomeState and :Some_State

Value descriptions

It's possible to associate a description with a value by passing a {value, description} tuple inside the values list, which becomes a keyword list:

defmodule MyApp.TicketStatus do
  use Ash.Type.Enum,
    values: [
      open: "An open ticket",
      closed: "A closed ticket"
    ]
end

This can be used by extensions to provide detailed descriptions of enum values.

The description of a value can be retrieved with description/1:

MyApp.TicketStatus.description(:open)
iex> "An open ticket"

Summary

Callbacks

The description of the value, if existing

finds the valid value that matches a given input term

true if a given term matches a value

The list of valid values (not all input types that match them)

Callbacks

@callback description(atom()) :: String.t() | nil

The description of the value, if existing

@callback match(term()) :: {:ok, atom()} | :error

finds the valid value that matches a given input term

@callback match?(term()) :: boolean()

true if a given term matches a value

@callback values() :: [atom()]

The list of valid values (not all input types that match them)