Basic state with AASM
suggest changeUsually you’ll end up creating models which will contain a state, and that state will be changing during the lifespan of the object.
AASM is a finite-state-machine library. It keeps state changes on the model, which fits the fat model, skinny controller approach: the model owns its state, the transitions, and the events those transitions trigger.
Add this to the Gemfile:
gem 'aasm'
Consider an App where the user Quotes a product for a price.
class Quote < ApplicationRecord
include AASM
aasm do
state :requested, initial: true # User sees a product and requests a quote
state :priced # Seller sets the price
state :paid # Buyer pays the price
state :canceled # The buyer is not willing to pay the price
state :completed # The product has been delivered.
event :price do
transitions from: :requested, to: :priced
end
event :pay do
transitions from: :priced, to: :paid, success: :set_payment_date
end
event :complete do
transitions from: :paid, to: :completed, guard: :product_delivered?
end
event :cancel do
transitions from: [:requested, :priced], to: :canceled
transitions from: :paid, to: :canceled, success: :reverse_charges
end
end
private
def set_payment_date
update paid_at: Time.zone.now
end
end
The Quote class’ states can go however it’s best for your process.
States can be named in the past tense, as above, or in another tense, such as pricing, paying, or delivering. Past-tense names often match a completed end state and the event names better.
Note: Do not use Ruby or Rails reserved words as state names, such as valid, end, or being.
Having defined the states and transitions we can now access some methods created by AASM.
For example:
Quote.priced # quotes currently in the priced state
quote.priced? # true when this quote is priced
quote.price! # runs the event that moves requested -> priced
Each event has transitions. A transition decides how the state changes when the event runs. If the current state has no matching transition, AASM raises an error.
The events and transitions also have some other callbacks, for example
guard: :product_delivered?
AASM calls product_delivered?, which must return a boolean. When it returns false and no other transition applies, the state does not change.
success: :reverse_charges
When that transition succeeds, AASM calls reverse_charges.
AASM has more callbacks than this. These are enough to add states to a first model. The product_delivered? and reverse_charges methods are part of your model; they are not defined by AASM.