The intention is to allow defined values for an attribute only and allow predefined transitions from one state to another only. For example, state A can be transferred in state B or state C, but state B can not be transferred in state C. In addition AASM offers some callback methods to controll transitions or do something before or after a transition.
I used AASM within a user model to ensure that the user states can only be changed on predefined ways. See the example:
# THE STATE MACHINE ----------------------------------------------------------
INITIAL_STATE = :pending
STATES = {
INITIAL_STATE => 'new user accounts initial state',
:waiting => 'new user account is waiting for confirmation',
:confirmed => 'user confirmed the registration',
:changing_email => 'user changed its email address',
:blocked => 'user can not log in',
:anonymized => 'personal user data deleted',
:not_deletable => 'can not delete user, because he has some content'
}
include AASM
attr_protected :state
aasm({:column => :state}) do
STATES.keys.each do |key|
state(key, (key == INITIAL_STATE ? {:initial => true} : {}))
end
# creates instance methods confirm, confirm! and confirmed? for later usage
event :confirm do
transitions :to => :confirmed, :from => :waiting
transitions :to => :confirmed, :from => :blocked
transitions :to => :confirmed, :from => :changing_email
transitions :to => :confirmed, :from => :not_deletable
end
end
In the event block I define how a user state can become confirmed. Therefore the user.state attribute has to be "waiting", "blocked", "changing_email" or "not_deleteable". In these cases you can call some magic methods which AASM brings in.
user.confirmed?
# => false
Now you can confirm the user.
user.confirm
user.state
# => confirmed
Or
user.confirm!
# => true
user.state
# => confirmed
Now
user.confirmed?
# => true
If my user has the state "anonymized" then I can't confirm it and will get an error. This way my user instances have well defined states at any time. I can't make a mistake while changing a user state. I do it with the defined methods from AASM only. Only defined states and defined transitions are possible to do.