Skip to content

Instantly share code, notes, and snippets.

@accuser

accuser/user.ex Secret

Last active March 22, 2017 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save accuser/115dcc656493bdbfd644e417adc63766 to your computer and use it in GitHub Desktop.
Save accuser/115dcc656493bdbfd644e417adc63766 to your computer and use it in GitHub Desktop.
defmodule User do
use GenServer
def start_link(user_id) do
GenServer.start_link(__MODULE__, [user_id], name: user_id)
end
def init(user_id) do
User.Entity.start_link(user_id)
end
# ...
# Callbacks
def handle_call(%ActivateUser{}, _from, user) do
user
|> User.activate
end
# ...
end
defmodule User.Entity do
use Ecto.Schema
schema "users" do
field :email, :string
field :active, :boolean, default: false
end
@doc """
Activate the user.
"""
def activate(pid) do
Agent.get_and_update(pid, fn user ->
event = %UserActivated{user_id: user.id}
state = User.apply(user, event)
{event, state}
end)
end
def apply(%User{} = user, %UserActivated{}) do
user
|> changeset(%{active: true}, [:active])
|> apply_changes
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment