Skip to content

Commit

Permalink
Adds a default transition_changeset/4 (#20)
Browse files Browse the repository at this point in the history
Why:

* Fixes #17

This change addresses the need by:

* Adding a default implementation of transition_changeset/4 that we had
  removed
  • Loading branch information
zamith authored Sep 8, 2023
1 parent 50ccc70 commit 31b215f
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion config/test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ config :fsmx, Fsmx.Repo,
database: "fsmx_test",
pool: Ecto.Adapters.SQL.Sandbox

config :logger, level: :warn
config :logger, level: :warning
1 change: 1 addition & 0 deletions lib/fsmx/fsm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ defmodule Fsmx.Fsm do
def before_transition(struct, _from, _to, _state_field), do: {:ok, struct}

if Code.ensure_loaded?(Ecto) do
def transition_changeset(changeset, _from, _to, _params), do: changeset
def transition_changeset(changeset, _from, _to, _params, _state_field), do: changeset
def after_transition_multi(struct, _from, _to, _state_field), do: {:ok, struct}
end
Expand Down
12 changes: 11 additions & 1 deletion test/fsmx/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ defmodule Fsmx.EctoTest do

alias Ecto.Multi
alias Fsmx.Repo
alias Fsmx.TestEctoSchemas.{Simple, WithCallbacks, WithSeparateFsm, MultiState}
alias Fsmx.TestEctoSchemas.{Simple, WithCallbacks, WithSeparateFsm, MultiState, WithChangesets}

describe "transition_changeset/2" do
test "returns a changeset" do
Expand Down Expand Up @@ -86,6 +86,16 @@ defmodule Fsmx.EctoTest do
end
end

describe "transition/4" do
test "works even if you don't define all possibilities" do
one = %WithChangesets{state: "one"}

three = Fsmx.transition_changeset(one, "three", %{})

assert Ecto.Changeset.get_change(three, :state) == "three"
end
end

describe "transition_multi/5" do
test "adds a transition changeset to the given multi" do
one = %Simple{state: "1"}
Expand Down
21 changes: 21 additions & 0 deletions test/support/test_ecto_schemas/with_changesets.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
defmodule Fsmx.TestEctoSchemas.WithChangesets do
use Ecto.Schema

import Ecto.Changeset

schema "test" do
field(:state, :string, default: "one")
field(:data, :map)
end

use Fsmx.Struct,
transitions: %{
"one" => ["two", "three"]
}

def transition_changeset(changeset, "one", "two", params) do
changeset
|> cast(params, [:data])
|> validate_required([:data])
end
end

0 comments on commit 31b215f

Please sign in to comment.