-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add
next_state
builtin change.
When there is only a single possible next state that can be transitioned into, we can automatically transition into that state.
- Loading branch information
Showing
3 changed files
with
105 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
defmodule AshStateMachine.BuiltinChanges.NextState do | ||
@moduledoc """ | ||
Given the action and the current state, attempt to find the next state to | ||
transition into. | ||
""" | ||
use Ash.Resource.Change | ||
|
||
def change(changeset, _opts, _) do | ||
attribute = AshStateMachine.Info.state_machine_state_attribute!(changeset.resource) | ||
|
||
current_state = Map.get(changeset.data, attribute) | ||
|
||
changeset.resource | ||
|> AshStateMachine.Info.state_machine_transitions(changeset.action.name) | ||
|> Enum.filter(fn | ||
%{from: from} when is_list(from) -> current_state in from | ||
%{from: from} -> current_state == from | ||
end) | ||
|> Enum.flat_map(fn | ||
%{to: to} when is_list(to) -> to | ||
%{to: to} -> [to] | ||
end) | ||
|> Enum.uniq() | ||
|> Enum.reject(&(&1 == :*)) | ||
|> case do | ||
[to] -> | ||
AshStateMachine.transition_state(changeset, to) | ||
|
||
[] -> | ||
Ash.Changeset.add_error(changeset, "Cannot determine next state: no next state available") | ||
|
||
_ -> | ||
Ash.Changeset.add_error( | ||
changeset, | ||
"Cannot determine next state: multiple next states available" | ||
) | ||
end | ||
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