Skip to content

Instantly share code, notes, and snippets.

@hl
Created December 6, 2023 12:55
Show Gist options
  • Save hl/2ba6690e7c686d020b87791a4f107275 to your computer and use it in GitHub Desktop.
Save hl/2ba6690e7c686d020b87791a4f107275 to your computer and use it in GitHub Desktop.
defmodule James do
@moduledoc """
Agent: James Bond
"""
defmodule State do
@moduledoc """
Data module to defined and modify state.
"""
defstruct [:id, :name]
@opaque t :: %__MODULE__{
id: id(),
name: name() | nil
}
@type key :: atom()
@type value :: any()
@type id :: String.t()
@type name :: String.t()
@spec new(id()) :: t()
def new(id), do: struct(__MODULE__, id: id)
@spec get(t, key()) :: value()
def get(%__MODULE__{} = state, key), do: Map.get(state, key)
@spec put(t, atom(), value()) :: t()
def put(%__MODULE__{} = state, key, value), do: Map.put(state, key, value)
end
use Agent
@spec start_link(State.id()) :: Agent.on_start()
def start_link(id) do
Agent.start_link(State, :new, [id], name: __MODULE__)
end
@spec state() :: State.t()
def state do
Agent.get(__MODULE__, Function, :identity, [])
end
@spec get(State.key()) :: any()
def get(key) do
Agent.get(__MODULE__, State, :get, [key])
end
@spec put(State.key(), State.value()) :: :ok
def put(key, value) do
Agent.update(__MODULE__, State, :put, [key, value])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment