Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for custom error messages on guard functions #35

Merged
merged 1 commit into from
May 2, 2018

Conversation

joaomdmoura
Copy link
Owner

Relates to issue #34

This commit will add the ability to declare a custom error
message for guard functions and properly propagate it.

Guard conditions will allow the transition if it returns anything other than a tuple with {:error, "cause"}:

  • {:error, "cause"}: Transition won't be allowed.
  • _ (anything else): Guard clause will allow the transition.

Example:

defmodule YourProject.UserStateMachine do
  use Machinery,
    states: ["created", "complete"],
    transitions: %{"created" => "complete"}

  # Guard the transition to the "complete" state.
  def guard_transition(struct, "complete") do
    if Map.get(struct, :missing_fields) == true do
      {:error, "There are missing fields"}
    end
  end
end

When trying to transition an struct that is blocked by its guard clause you will
have the following return:

blocked_struct = %TestStruct{state: "created", missing_fields: true}
Machinery.transition_to(blocked_struct, TestStateMachineWithGuard, "completed")

# {:error, "There are missing fields"}

This commit will add the ability to declare a custom error
message for guard functions and properly propagate it.
@joaomdmoura joaomdmoura force-pushed the guard-transition-cause branch from 1292003 to 3fac75a Compare May 1, 2018 14:26
Repository owner deleted a comment from coveralls May 1, 2018
@wfgilman
Copy link

wfgilman commented May 1, 2018

This looks great! Can the custom error be any data type or must it be a string?

@joaomdmoura
Copy link
Owner Author

joaomdmoura commented May 1, 2018

@wfgilman 🤔 yup, but keep in mind this will also be used by the dashboard, so in order to the dashboard work properly it should probably be a string or a number tops, but the library itself will work just fine with any type.

@wfgilman
Copy link

wfgilman commented May 1, 2018 via email

@joaomdmoura joaomdmoura merged commit d940e7e into master May 2, 2018
@joaomdmoura joaomdmoura deleted the guard-transition-cause branch May 2, 2018 21:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants