Further separate module agents and module impl

Add Omnibot.Module.Agent which implements the basic agent cfg + state
persistence functionality, which is then included in the Omnibot.Module.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2020-06-14 18:46:19 -04:00
parent 0b01f3524e
commit 871b7771fe
3 changed files with 44 additions and 23 deletions

43
lib/module/agent.ex Normal file
View File

@@ -0,0 +1,43 @@
defmodule Omnibot.Module.Agent do
defmacro __using__([]) do
quote do
import Omnibot.Module.Agent
alias Omnibot.Module
use Agent
def start_link(opts) do
cfg = opts[:cfg]
state = opts[:state] || on_init(cfg)
IO.inspect({__MODULE__, state})
Module.Agent.start_link(cfg, state, opts)
end
def cfg, do: Module.Agent.cfg(__MODULE__)
def state, do: Module.Agent.state(__MODULE__)
def update_state(update, timeout \\ 5000),
do: Module.Agent.update_state(__MODULE__, update, timeout)
end
end
def start_link(cfg, state, opts) do
Agent.start_link(fn -> {cfg, state} end, opts)
end
def cfg(agent) do
Agent.get(agent, fn {cfg, _} -> cfg end)
end
def state(agent) do
Agent.get(agent, fn {_, state} -> state end)
end
def update_state(agent, update, timeout \\ 5000) do
Agent.update(
agent,
fn {cfg, state} -> {cfg, apply(update, [state])} end,
timeout
)
end
end

View File

@@ -32,7 +32,6 @@ defmodule Omnibot.Module.Base do
quote do quote do
alias Omnibot.{Irc, Module} alias Omnibot.{Irc, Module}
import Omnibot.Module.Base import Omnibot.Module.Base
require Logger
@behaviour Module.Base @behaviour Module.Base

View File

@@ -2,28 +2,7 @@ defmodule Omnibot.Module do
defmacro __using__([]) do defmacro __using__([]) do
quote do quote do
use Omnibot.Module.Base use Omnibot.Module.Base
use Agent use Omnibot.Module.Agent
def start_link(opts) do
cfg = opts[:cfg]
Agent.start_link(fn -> {cfg, on_init(cfg)} end, opts ++ [name: __MODULE__])
end
def cfg do
Agent.get(__MODULE__, fn {cfg, _} -> cfg end)
end
def state do
Agent.get(__MODULE__, fn {_, state} -> state end)
end
def update_state(update, timeout \\ 5000) do
Agent.update(
__MODULE__,
fn {cfg, state} -> {cfg, apply(update, [state])} end,
timeout
)
end
end end
end end
end end