StateMachine.Ecto (state_machine v0.1.6)

This addition makes StateMachine fully compatible with Ecto.

State setter and getter are abstracted in order to provide a way to update a state in the middle of transition for a various types of models. With Ecto, we call change() |> Repo.update. We also wrap every event in transaction, which is rolled back if transition fails to finish. This unlocks a lot of beautiful effects. For example, you can enqueue some tasks into db-powered queue in callbacks, and if transition failes, those tasks will naturally disappear.

Usage

To use Ecto, simply pass repo param to defmachine, you can optionally pass a name of the Ecto.Type implementation, that will be generated automatically under state machine namespace:

defmodule EctoMachine do
  use StateMachine

  defmachine field: :state, repo: TestApp.Repo, ecto_type: CustomMod do
    state :resting
    state :working

    # ...
  end
end

In your schema you can refer to state type as EctoMachine.CustomMod, with ecto_type omitted it would generate EctoMachine.StateType. This custom type is needed to transparently use atoms as states.

Link to this section Summary

Functions

This macro defines an Ecto.Type implementation inside of StateMachine namespace. The default name is StateType, but you can supply any module name. The purpose of this is to be able to cast string into atom and back safely, validating it against StateMachine defition.

Link to this section Functions

Link to this macro

define_ecto_type(kind)

(macro)

This macro defines an Ecto.Type implementation inside of StateMachine namespace. The default name is StateType, but you can supply any module name. The purpose of this is to be able to cast string into atom and back safely, validating it against StateMachine defition.

Link to this macro

define_enum(variants)

(macro)