Packages

This project provides boilerplate modules for using Agents for common persistence use-cases. I will add to this over time, as my own needs for Agent boilerplate arises.

Current section

Files

Jump to
stateful_agents lib stateful_agents.ex
Raw

lib/stateful_agents.ex

defmodule StatefulAgents do
@moduledoc """
StatefulAgents is a repository of Agents that I use frequently. These are
needed all the time when developing, so I just made a library of them.
"""
defmodule MapAgent do
use Agent
@doc """
iex> alias StatefulAgents.MapAgent
...> {:ok, pid} = MapAgent.start
...> assert is_pid(pid)
true
"""
def start, do: Agent.start(fn -> %{} end)
@doc """
iex> alias StatefulAgents.MapAgent
...> {:ok, pid} = MapAgent.start
...> assert is_pid(pid)
true
...> MapAgent.stop(pid)
:ok
"""
def stop(pid), do: Agent.stop(pid)
@doc """
iex> alias StatefulAgents.MapAgent
...> {:ok, pid} = MapAgent.start
...> assert is_pid(pid)
true
...> map = MapAgent.get(pid)
...> assert is_map(map)
true
"""
def get(pid), do: Agent.get(pid, fn state -> state end)
@doc """
iex> alias StatefulAgents.MapAgent
...> {:ok, pid} = MapAgent.start
...> assert is_pid(pid)
true
...> MapAgent.set(pid, %{foo: "bar", baz: "bong"})
:ok
"""
def set(pid, state) when is_map(state) do
Agent.update(pid, fn _ -> state end)
end
def set(_pid, state) do
raise ArgumentError, message: "set/1 requires argument of type map. Got: '" <> IO.inspect(state) <> "'"
end
end
defmodule BooleanAgent do
use Agent
@doc """
Stores a boolean as the Agent's state. Provides helper functions to access
and set state in the Agent.
iex> alias StatefulAgents.BooleanAgent
...> {:ok, pid} = BooleanAgent.start_link
...> is_pid(pid)
true
"""
def start_link, do: Agent.start_link(fn -> false end, [name: __MODULE__])
@doc """
iex> alias StatefulAgents.BooleanAgent
...> {:ok, pid} = BooleanAgent.start_link
...> assert is_pid(pid)
true
...> value = BooleanAgent.get
...> is_boolean(value)
true
"""
def get, do: Agent.get(__MODULE__, fn state -> state end)
@doc """
iex> alias StatefulAgents.BooleanAgent
...> {:ok, pid} = BooleanAgent.start_link
...> assert is_pid(pid)
true
...> BooleanAgent.set(true)
:ok
"""
def set(state) when is_boolean(state) do
Agent.update(__MODULE__, fn _ -> state end)
end
def set(state) do
raise ArgumentError, message: "set/1 requires argument of type boolean. Got: '" <> IO.inspect(state) <> "'"
end
end
end