Let's assume a very simple Payment
class like this:
class Payment
include AASM
aasm do
state :created
state :paid
state :refunded
event :pay do
transitions from :created, to :paid
end
end
end
So one would call payment.pay
to trigger the payment, making the appropriate API Calls.
It's very important that the transition from created
to paid
only happens if the payment actually succeeds.
1) I would assume the API Calls should be put in a before
callback in the :pay
event, but that would not halt the transition if the API call was unsuccessful (let's assume the API call does NOT raise an exception, it just returns a status).
2) I then thought that I should combine the before
callback with a guard; use the before
callback to call the API, and set it's result on the model (using an attr_accessor
for instance). Then the guard would only allow it transition from the created
to paid
state if the payment was successful.
Is that the idiomatic way of handling such an event transition in a state machine with aasm? I read all stack overflow's questions tagged aasm
and the gem documentation and still have questions about what's the best way to make these safe transitions.