-
-
Save accuser/115dcc656493bdbfd644e417adc63766 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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