Gearbox - A functional state machine with an easy-to-use API, inspired by both Fsm and Machinery

I’m not 100% sure if I’m getting your question still, but here goes.

Gearbox does not currently ship with a data concept, which means it can’t really perfectly do what you want. But that’s also sort of the point of it (I’m open to suggestions/counter-argument). If you want more complex data in a state machine, you can build your own abstraction over it. The only thing that Gearbox wants to do is to help you transition from a state to another.

For the fun of it I did a quick hack to show what a contrived example of Regex matcher implementation would look like, the idea of this is to show that Gearbox does a very simple thing, and if you need complex data modelling you can abstract over it. (Like I said, still open to debate for this)


defmodule RegexMachine do
  use Gearbox,
    states: ~w(a b c),
    transitions: %{
      "a" => ["a", "b"],
      "b" => ["b", "c"]
    }
end

defmodule CustomRegex do
  def match(string) do
    run(string)
  end

  def run(string) when is_binary(string) do
    string
    |> String.split("", trim: true)
    |> run()
  end

  def run([_head | []]) do
    :match
  end

  def run([current | [next | _] = another] = chars) when is_list(chars) do
    map = %{state: current} # this is a bit of a hack because Gearbox currently expects a map

    case Gearbox.transition(map, RegexMachine, next) do
      {:ok, state} ->
        run(another)
      {:error, reason} ->
        :failed
    end
  end
end

CustomRegex.match("aaabbbc")

You can see how in that contrived example, all Gearbox does is to help you check the next state, the idea of data is provided by CustomRegex itself.

Note: It’s probably worth noting that Gearbox mainly stemmed from ecommerce-style applications where we see random state transitions that should never happen (a transaction going from pendingrefunded for example).

I hope that helps answers your question, if not then definitely ask away!

1 Like