Skip to content

Commit

Permalink
Add behaviour to __using__ macro
Browse files Browse the repository at this point in the history
Signed-off-by: Nikita Localhost <[email protected]>
  • Loading branch information
nikitalocalhost committed Feb 7, 2025
1 parent 31b215f commit 3388445
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/fsmx/fsm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ defmodule Fsmx.Fsm do
{:ok, struct} | {:error, any}

if Code.ensure_loaded?(Ecto) do
@callback transition_changeset(Ecto.Schema.t(), Fsmx.state_t(), Fsmx.state_t(), map()) ::
Ecto.Changeset.t()
@callback transition_changeset(Ecto.Schema.t(), Fsmx.state_t(), Fsmx.state_t(), map(), atom()) ::
Ecto.Changeset.t()
@callback after_transition_multi(struct, Fsmx.state_t(), Fsmx.state_t(), atom()) ::
Expand All @@ -50,6 +52,11 @@ defmodule Fsmx.Fsm do
{state_field, _} = Code.eval_quoted(Keyword.get(opts, :state_field, :state))

quote do
if not Module.get_attribute(__MODULE__, :__fsmx__behaviour, false) do
@behaviour Fsmx.Fsm
Module.put_attribute(__MODULE__, :__fsmx__behaviour, true)
end

@before_compile unquote(__MODULE__)

def __fsmx__(unquote(state_field), :transitions),
Expand All @@ -61,11 +68,17 @@ defmodule Fsmx.Fsm do

defmacro __before_compile__(_env) do
quote generated: false do
@impl Fsmx.Fsm
def before_transition(struct, _from, _to, _state_field), do: {:ok, struct}

if Code.ensure_loaded?(Ecto) do
@impl Fsmx.Fsm
def transition_changeset(changeset, _from, _to, _params), do: changeset

@impl Fsmx.Fsm
def transition_changeset(changeset, _from, _to, _params, _state_field), do: changeset

@impl Fsmx.Fsm
def after_transition_multi(struct, _from, _to, _state_field), do: {:ok, struct}
end
end
Expand Down

0 comments on commit 3388445

Please sign in to comment.