View Source Parameter.Enum (Parameter v0.5.0)
Enum type that represents a group of constants that have a value with a associated key.
example
Example
defmodule MyApp.UserParam do
use Parameter.Schema
enum Status do
value "userOnline", as: :user_online
value "userOffline", as: :user_offline
end
param do
field :first_name, :string, key: "firstName"
field :status, MyApp.UserParam.Status
end
end
The Status
enum should automatically translate the userOnline
and userOffline
values when loading
to the respective atom values.
iex> Parameter.load(MyApp.UserParam, %{"firstName" => "John", "status" => "userOnline"})
{:ok, %{first_name: "John", status: :user_online}}
...> # It also uses the key for dumping:
...> Parameter.dump(MyApp.UserParam, %{first_name: "John", status: :user_online})
{:ok, %{"firstName" => "John", "status" => "userOnline"}}
Enum also supports a shorter version if the key and value are already the same:
defmodule MyApp.UserParam do
...
enum Status, values: [:user_online, :user_offline]
...
end
iex> Parameter.load(MyApp.UserParam, %{"firstName" => "John", "status" => "user_online"})
{:ok, %{first_name: "John", status: :user_online}}
It's also possible to create enums in different modules by using the
enum/1
macro:
defmodule MyApp.Status do
import Parameter.Enum
enum do
value "userOnline", as: :user_online
value "userOffline", as: :user_offline
end
end
defmodule MyApp.UserParam do
use Parameter.Schema
alias MyApp.Status
param do
field :first_name, :string, key: "firstName"
field :status, Status
end
end
And it's short version:
enum values: [:user_online, :user_offline]