AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid, NoBrainer, Dynamoid)
AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid, NoBrainer, Dynamoid)
This package contains AASM, a library for adding finite state machines to Ruby classes.
AASM started as the acts_as_state_machine plugin but has evolved into a more generic library that no longer targets only ActiveRecord models. It currently provides adapters for many ORMs but it can be used for any Ruby class, no matter what parent class it has (if any).
Take a look at the README_FROM_VERSION_5_TO_6 for details how to switch from version 5.x to 6.0 of AASM.
Take a look at the README_FROM_VERSION_3_TO_4 for details how to switch from version 3.x to 4.0 of AASM.
Adding a state machine is as simple as including the AASM module and start defining states and events together with their transitions:
class Job
include AASM
aasm do
state :sleeping, initial: true
state :running, :cleaning
event :run do
transitions from: :sleeping, to: :running
end
event :clean do
transitions from: :running, to: :cleaning
end
event :sleep do
transitions from: [:running, :cleaning], to: :sleeping
end
end
endThis provides you with a couple of public methods for instances of the class Job:
job = Job.new
job.sleeping? # => true
job.may_run? # => true
job.run
job.running? # => true
job.sleeping? # => false
job.may_run? # => false
job.run # => raises AASM::InvalidTransitionIf you don't like exceptions and prefer a simple true or false as response, tell
AASM not to be whiny:
class Job
...
aasm whiny_transitions: false do
...
end
end
job.running? # => true
job.may_run? # => false
job.run # => falseWhen firing an event, you can pass a block to the method, it will be called only if the transition succeeds :
job.run do
job.user.notify_job_ran # Will be called if job.may_run? is true
endYou can define a number of callbacks for your events, transitions and states. These methods, Procs or classes will be called when certain criteria are met, like entering a particular state:
…In this case do_something is called before actually entering the state sleeping,
while notify_somebody is called after the transition run (from sleeping to running)
is finished.
AASM will also initialize LogRunTime and run the call method for you after the transition from running to finished in the example above. You can pass arguments to the class by defining an initialize method on it, like this:
Note that Procs are executed in the context of a record, it means that you don't need to expect the record as an argument, just call the methods you need.
class LogRunTime
# optional args parameter can be omitted, but if you define initialize
# you must accept the model instance as the first parameter to it.
def initialize(job, args = {})
@job = job
end
def call
log "Job was running for #{@job.run_time} seconds"
end
endYou can pass parameters to events:
job = Job.new
job.run(:defragmentation)All guards and after callbacks will receive these parameters. In this case set_process would be called with
:defragmentation argument.
If the first argument to the event is a state (e.g. :running or :finished), the first argument is consumed and
the state machine will attempt to transition to that state. Add comma separated parameter for guards and callbacks
job = Job.new
job.run(:running, :defragmentation)In this case set_process won't be called, job will transition to running state and callback will receive
:defragmentation as parameter
In case of an error during the event processing the error is rescued and passed to :error
callback, which can handle it or re-raise it for further propagation.
Also, you can define a method that will be called if any event fails:
def aasm_event_failed(event_name, old_state_name)
# use custom exception/messages, report metrics, etc
endDuring the transition's :after callback (and reliably only then, or in the global
after_all_transitions callback) you can access the originating state (the from-state)
and the target state (the to state), like this:
def set_process(name)
logger.info "from #{aasm.from_state} to #{aasm.to_state}"
endHere you can see a list of all possible callbacks, together with their order of calling:
…Use event's after_commit callback if it should be fired after database update.
While running the callbacks you can easily retrieve the name of the event triggered
by using aasm.current_event:
# taken the example callback from above
def do_something
puts "triggered #{aasm.current_event}"
endand then
job = Job.new
# without bang
job.sleep # => triggered :sleep
# with bang
job.sleep! # => triggered :sleep!Let's assume you want to allow particular transitions only if a defined condition is
given. For this you can set up a guard per transition, which will run before actually
running the transition. If the guard returns false the transition will be
denied (raising AASM::InvalidTransition):
…You can even provide a number of guards, which all have to succeed to proceed
def walked_the_dog?; ...; end
event :sleep do
transitions from: :running, to: :sleeping, guards: [:cleaning_needed?, :walked_the_dog?]
endIf you want to provide guards for all transitions within an event, you can use event guards
event :sleep, guards: [:walked_the_dog?] do
transitions from: :running, to: :sleeping, guards: [:cleaning_needed?]
transitions from: :cleaning, to: :sleeping
endIf you prefer a more Ruby-like guard syntax, you can use if and unless as well:
event :clean do
transitions from: :running, to: :cleaning, if: :cleaning_needed?
end
event :sleep do
transitions from: :running, to: :sleeping, unless: :cleaning_needed?
end
endYou can invoke a Class instead of a method if the Class responds to call
event :sleep do
transitions from: :running, to: :sleeping, guards: Dog
end class Dog
def call
cleaning_needed? && walked?
end
...
endIn the event of having multiple transitions for an event, the first transition that successfully completes will stop other transitions in the same event from being processed.
require 'aasm'
class Job
include AASM
aasm do
state :stage1, initial: true
state :stage2
state :stage3
state :completed
event :stage1_completed do
transitions from: :stage1, to: :stage3, guard: :stage2_completed?
transitions from: :stage1, to: :stage2
end
end
def stage2_completed?
true
end
end
job = Job.new
job.stage1_completed
job.aasm.current_state # stage3You can define transition from any defined state by omitting from:
event :abort do
transitions to: :aborted
endYou can define display name for state using :display option
class Job
include AASM
aasm do
state :stage1, initial: true, display: 'First Stage'
state :stage2
state :stage3
end
end
job = Job.new
job.aasm.human_state
Multiple state machines per class are supported. Be aware though that AASM has been
built with one state machine per class in mind. Nonetheless, here's how to do it (see below). Please note that you will need to specify database columns for where your pertinent states will be stored - we have specified two columns move_state and work_state in the example below. See the Column name & migration section for further info.
…AASM doesn't prohibit to define the same event in more than one state
machine. If no namespace is provided, the latest definition "wins" and
overrides previous definitions. Nonetheless, a warning is issued:
SimpleMultipleExample: overriding method 'run'!.
Alternatively, you can provide a namespace for each state machine. When a namespace is used, event methods are defined with the namespace as a suffix, preventing collisions between state machines that share event names:
…All AASM class- and instance-level aasm methods accept a state machine selector.
So, for example, to use inspection on a class level, you have to use
SimpleMultipleExample.aasm(:move).states.map(&:name)
# => [:standing, :walking, :running]Allow an event to be bound to another
…AASM automatically generates constants for each status so you don't have to explicitly define them.
class Foo
include AASM
aasm do
state :initialized
state :calculated
state :finalized
end
end
> Foo::STATE_INITIALIZED
#=> :initialized
> Foo::STATE_CALCULATED
#=> :calculatedAASM allows you to easily extend AASM::Base for your own application purposes.
Let's suppose we have common logic across many AASM models. We can embody this logic in a sub-class of AASM::Base.
…When we declare our model that has an AASM state machine, we simply declare the AASM block with a :with_klass key to our own class.
class SimpleCustomExample
include AASM
# Let's build an AASM state machine with our custom class.
aasm with_klass: CustomAASMBase do
requires_guards!
count_transitions!
state :initialised, initial: true
state :filled_out
state :authoNo open issues yet, or sync has not completed.