Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

aasm

> 后端框架
Open source

AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid, NoBrainer, Dynamoid)

5.2K stars0 likes2 views
WebsiteGitHub

About

AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid, NoBrainer, Dynamoid)

AASM - Ruby state machines

Index

  • Upgrade from version 5 to 6
  • Upgrade from version 3 to 4
  • Usage
    • Callbacks
      • Lifecycle
      • The current event triggered
    • Guards
    • Transitions
    • Multiple state machines per class
      • Handling naming conflicts between multiple state machines
      • Binding event
    • Auto-generated Status Constants
    • Extending AASM
    • ActiveRecord
    • Bang events
    • Timestamps
    • ActiveRecord enums
    • Sequel
    • Dynamoid
    • Mongoid
    • Nobrainer
    • Redis
    • Automatic Scopes
    • Transaction support
    • Pessimistic Locking
    • Column name & migration
    • Log State Changes
    • Inspection
    • Warning output
    • RubyMotion support
    • Testing
      • RSpec
      • Minitest
        • Assertions
        • Expectations
  • Installation
    • Manually from RubyGems.org
    • Bundler
    • Building your own gems
  • Generators
  • Test suite with Docker
  • Latest changes
  • Questions?
  • Maintainers
  • Contributing
  • Warranty
  • License

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).

Upgrade from version 5 to 6

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.

Upgrade from version 3 to 4

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.

Usage

Adding a state machine is as simple as including the AASM module and start defining states and events together with their transitions:

ruby
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

end

This provides you with a couple of public methods for instances of the class Job:

ruby
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::InvalidTransition

If you don't like exceptions and prefer a simple true or false as response, tell AASM not to be whiny:

ruby
class Job
  ...
  aasm whiny_transitions: false do
    ...
  end
end

job.running?  # => true
job.may_run?  # => false
job.run       # => false

When firing an event, you can pass a block to the method, it will be called only if the transition succeeds :

ruby
  job.run do
    job.user.notify_job_ran # Will be called if job.may_run? is true
  end

Callbacks

You 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.

ruby
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
end

Parameters

You can pass parameters to events:

ruby
  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

ruby
  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

Error Handling

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:

ruby
def aasm_event_failed(event_name, old_state_name)
  # use custom exception/messages, report metrics, etc
end

During 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:

ruby
  def set_process(name)
    logger.info "from #{aasm.from_state} to #{aasm.to_state}"
  end

Lifecycle

Here 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.

The current event triggered

While running the callbacks you can easily retrieve the name of the event triggered by using aasm.current_event:

ruby
  # taken the example callback from above
  def do_something
    puts "triggered #{aasm.current_event}"
  end

and then

ruby
  job = Job.new

  # without bang
  job.sleep # => triggered :sleep

  # with bang
  job.sleep! # => triggered :sleep!

Guards

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

ruby
    def walked_the_dog?; ...; end

    event :sleep do
      transitions from: :running, to: :sleeping, guards: [:cleaning_needed?, :walked_the_dog?]
    end

If you want to provide guards for all transitions within an event, you can use event guards

ruby
    event :sleep, guards: [:walked_the_dog?] do
      transitions from: :running, to: :sleeping, guards: [:cleaning_needed?]
      transitions from: :cleaning, to: :sleeping
    end

If you prefer a more Ruby-like guard syntax, you can use if and unless as well:

ruby
    event :clean do
      transitions from: :running, to: :cleaning, if: :cleaning_needed?
    end

    event :sleep do
      transitions from: :running, to: :sleeping, unless: :cleaning_needed?
    end
  end

You can invoke a Class instead of a method if the Class responds to call

ruby
    event :sleep do
      transitions from: :running, to: :sleeping, guards: Dog
    end
ruby
  class Dog
    def call
      cleaning_needed? && walked?
    end
    ...
  end

Transitions

In 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.

ruby
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 # stage3

You can define transition from any defined state by omitting from:

ruby
event :abort do
  transitions to: :aborted
end

Display name for state

You can define display name for state using :display option

ruby
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

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.

…

Handling naming conflicts between multiple state machines

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

ruby
SimpleMultipleExample.aasm(:move).states.map(&:name)
# => [:standing, :walking, :running]

Binding event

Allow an event to be bound to another

…

Auto-generated Status Constants

AASM automatically generates constants for each status so you don't have to explicitly define them.

ruby
class Foo
  include AASM

  aasm do
    state :initialized
    state :calculated
    state :finalized
  end
end

> Foo::STATE_INITIALIZED
#=> :initialized
> Foo::STATE_CALCULATED
#=> :calculated

Extending AASM

AASM 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.

ruby
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 :autho

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyaasmactiverecordhacktoberfestmongoid

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架