Skip to content

Instantly share code, notes, and snippets.

@davidrichards
Created September 30, 2016 01:48
Show Gist options
  • Save davidrichards/694c7eb030c01b17b014cbaea3aad4f1 to your computer and use it in GitHub Desktop.
Save davidrichards/694c7eb030c01b17b014cbaea3aad4f1 to your computer and use it in GitHub Desktop.
Examples of using EctoStateMachine
defmodule Dummy.User do
use Dummy.Web, :model
use EctoStateMachine,
states: [:unconfirmed, :confirmed, :blocked, :admin],
events: [
[
name: :confirm,
from: [:unconfirmed],
to: :confirmed,
callback: fn(model) -> Ecto.Changeset.change(model, confirmed_at: Ecto.DateTime.utc) end # yeah you can bring your own code to these functions.
], [
name: :block,
from: [:confirmed, :admin],
to: :blocked
], [
name: :make_admin,
from: [:confirmed],
to: :admin
]
]
schema "users" do
field :name, :string
field :state, :string, default: "unconfirmed"
end
def changeset(struct, params) do
struct
|> cast(params, [:name])
end
end
defmodule Dummy.User do
use Dummy.Web, :model
use EctoStateMachine,
states: [:unconfirmed, :confirmed, :blocked, :admin],
events: [
[
name: :confirm,
from: [:unconfirmed],
to: :confirmed,
callback: fn(model) -> Ecto.Changeset.change(model, confirmed_at: Ecto.DateTime.utc) end # yeah you can bring your own code to these functions.
], [
name: :block,
from: [:confirmed, :admin],
to: :blocked
], [
name: :make_admin,
from: [:confirmed],
to: :admin
]
]
import Ecto.Changeset
schema "users" do
field :name, :string
field :state, :string, default: "unconfirmed"
end
def changeset(struct, params) do
struct
|> cast(params, [:name])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment