View Source TypedEnum (typed_enum v0.1.2)
A module to allow you to use Enum's in ecto schemas, while automatically deriving their type definition.
Usage:
defmodule InvoiceStatus do
use TypedEnum, values: [:paid, :open, :closed, :rejected, :processing]
end
And then in your schema(s):
defmodule Invoice do
schema("invoices") do
belongs_to :user, User
field :status, InvoiceStatus, default: :open
end
end
In this case the values will be dumped at the Database layer into strings.
table invoices:
user_id references -> users
status -> string/varchar/text/etc
In case you want to use it as a proper integer enum, make the :values
option be
a keyword list with the key the atom and value the integer to which it corresponds:
defmodule InvoiceStatus do
use TypedEnum, values: [processing: 0, open: 1, paid: 2, closed: 3, rejected: 4]
end
The usage is the same, but in this case the column value will be serialized to its integer representation instead of a string. You can still cast string values, and in your app logic deal with their atom versions.
Check the test cases to see examples.