- Upgrade from version 3 to 4
- Usage
- Callbacks
- Guards
- Transitions
- Multiple state machines per class
- Auto-generated Status Constants
- Extending AASM
- ActiveRecord
- Bang events
- ActiveRecord enums
- Sequel
- Dynamoid
- Mongoid
- Nobrainer
- Redis
- Automatic Scopes
- Transaction support
- Pessimistic Locking
- Column name & migration
- Inspection
- Warning output
- RubyMotion support
- Testing
- Installation
- 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).
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:
classJobincludeAASMaasmdostate:sleeping,:initial=>truestate:running,:cleaningevent:rundotransitions:from=>:sleeping,:to=>:runningendevent:cleandotransitions:from=>:running,:to=>:cleaningendevent:sleepdotransitions:from=>[:running,:cleaning],:to=>:sleepingendendendThis provides you with a couple of public methods for instances of the class Job:
job=Job.newjob.sleeping?# => truejob.may_run?# => truejob.runjob.running?# => truejob.sleeping?# => falsejob.may_run?# => falsejob.run# => raises AASM::InvalidTransitionIf you don't like exceptions and prefer a simple true or false as response, tell
AASM not to be whiny:
classJob
...
aasm:whiny_transitions=>falsedo
...
endendjob.running?# => truejob.may_run?# => falsejob.run# => falseWhen firing an event, you can pass a block to the method, it will be called only if the transition succeeds :
job.rundojob.user.notify_job_ran# Will be called if job.may_run? is trueendYou 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:
classJobincludeAASMaasmdostate:sleeping,:initial=>true,:before_enter=>:do_somethingstate:running,before_enter: Proc.new{do_something && notify_somebody}state:finishedafter_all_transitions:log_status_changeevent:run,:after=>:notify_somebodydobeforedolog('Preparing to run')endtransitions:from=>:sleeping,:to=>:running,:after=>Proc.new{|*args| set_process(*args)}transitions:from=>:running,:to=>:finished,:after=>LogRunTimeendevent:sleepdoafterdo
...
enderrordo |e|
...
endtransitions:from=>:running,:to=>:sleepingendenddeflog_status_changeputs"changing from #{aasm.from_state} to #{aasm.to_state} (event: #{aasm.current_event})"enddefset_process(name)
...
enddefdo_something
...
enddefnotify_somebody
...
endendclassLogRunTimedefcalllog"Job was running for X seconds"endendIn 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.
classLogRunTime# optional args parameter can be omitted, but if you define initialize# you must accept the model instance as the first parameter to it.definitialize(job,args={})@job=jobenddefcalllog"Job was running for #{@job.run_time} seconds"endendAlso, you can pass parameters to events:
job=Job.newjob.run(:running,:defragmentation)In this case the set_process would be called with :defragmentation argument.
Note that when passing arguments to a state transition, the first argument must be the desired end state. In the above example, we wish to transition to :running state and run the callback with :defragmentation argument. You can also pass in nil as the desired end state, and AASM will try to transition to the first end state defined for that event.
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:
defaasm_event_failed(event_name,old_state_name)# use custom exception/messages, report metrics, etcendDuring 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:
defset_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:
begineventbefore_all_eventseventbeforeeventguardstransitionguardsold_statebefore_exitold_stateexitafter_all_transitionstransitionafternew_statebefore_enternew_stateenter
...updatestate...
eventbefore_success# if persist successfultransitionsuccess# if persist successfuleventsuccess# if persist successfulold_stateafter_exitnew_stateafter_entereventaftereventafter_all_eventsrescueeventerroreventerror_on_all_eventsensureeventensureeventensure_on_all_eventsendWhile running the callbacks you can easily retrieve the name of the event triggered
by using aasm.current_event:
# taken the example callback from abovedefdo_somethingputs"triggered #{aasm.current_event}"endand then
job=Job.new# without bangjob.sleep# => triggered :sleep# with bangjob.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 or returning false itself):
classCleanerincludeAASMaasmdostate:idle,:initial=>truestate:cleaningevent:cleandotransitions:from=>:idle,:to=>:cleaning,:guard=>:cleaning_needed?endevent:clean_if_neededdotransitions:from=>:idle,:to=>:cleaningdoguarddocleaning_needed?endendtransitions:from=>:idle,:to=>:idleendevent:clean_if_dirtydotransitions:from=>:idle,:to=>:cleaning,:guard=>:if_dirty?endenddefcleaning_needed?falseenddefif_dirty?(status)status == :dirtyendendjob=Cleaner.newjob.may_clean?# => falsejob.clean# => raises AASM::InvalidTransitionjob.may_clean_if_needed?# => truejob.clean_if_needed!# idlejob.clean_if_dirty(:clean)# => falsejob.clean_if_dirty(:dirty)# => trueYou can even provide a number of guards, which all have to succeed to proceed
defwalked_the_dog?; ...;endevent:sleepdotransitions: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?]dotransitions:from=>:running,:to=>:sleeping,:guards=>[:cleaning_needed?]transitions:from=>:cleaning,:to=>:sleepingendIf you prefer a more Ruby-like guard syntax, you can use if and unless as well:
event:cleandotransitions:from=>:running,:to=>:cleaning,:if=>:cleaning_needed?endevent:sleepdotransitions:from=>:running,:to=>:sleeping,:unless=>:cleaning_needed?endendIn 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'classJobincludeAASMaasmdostate:stage1,:initial=>truestate:stage2state:stage3state:completedevent:stage1_completeddotransitionsfrom: :stage1,to: :stage3,guard: :stage2_completed?transitionsfrom: :stage1,to: :stage2endenddefstage2_completed?trueendendjob=Job.newjob.stage1_completedjob.aasm.current_state# stage3Multiple 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:
classSimpleMultipleExampleincludeAASMaasm(:move)dostate:standing,:initial=>truestate:walkingstate:runningevent:walkdotransitions:from=>:standing,:to=>:walkingendevent:rundotransitions:from=>[:standing,:walking],:to=>:runningendevent:holddotransitions:from=>[:walking,:running],:to=>:standingendendaasm(:work)dostate:sleeping,:initial=>truestate:processingevent:startdotransitions:from=>:sleeping,:to=>:processingendevent:stopdotransitions:from=>:processing,:to=>:sleepingendendendsimple=SimpleMultipleExample.newsimple.aasm(:move).current_state# => :standingsimple.aasm(:work).current# => :sleepingsimple.startsimple.aasm(:move).current_state# => :standingsimple.aasm(:work).current# => :processingAASM 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:
classNamespacedMultipleExampleincludeAASMaasm(:status)dostate:unapproved,:initial=>truestate:approvedevent:approvedotransitions:from=>:unapproved,:to=>:approvedendevent:unapprovedotransitions:from=>:approved,:to=>:unapprovedendendaasm(:review_status,namespace: :review)dostate:unapproved,:initial=>truestate:approvedevent:approvedotransitions:from=>:unapproved,:to=>:approvedendevent:unapprovedotransitions:from=>:approved,:to=>:unapprovedendendendnamespaced=NamespacedMultipleExample.newnamespaced.aasm(:status).current_state# => :unapprovednamespaced.aasm(:review_status).current_state# => :unapprovednamespaced.approve_reviewnamespaced.aasm(:review_status).current_state# => :approvedAll 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
classExampleincludeAASMaasm(:work)dostate:sleeping,:initial=>truestate:processingevent:startdotransitions:from=>:sleeping,:to=>:processingendevent:stopdotransitions:from=>:processing,:to=>:sleepingendendaasm(:question)dostate:answered,:initial=>truestate:askedevent:ask,:binding_event=>:startdotransitions:from=>:answered,:to=>:askedendevent:answer,:binding_event=>:stopdotransitions:from=>:asked,:to=>:answeredendendendexample=Example.newexample.aasm(:work).current_state#=> :sleepingexample.aasm(:question).current_state#=> :answeredexample.askexample.aasm(:work).current_state#=> :processingexample.aasm(:question).current_state#=> :askedAASM automatically generates constants for each status so you don't have to explicitly define them.
classFooincludeAASMaasmdostate:initializedstate:calculatedstate:finalizedendend
> 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.
classCustomAASMBase < AASM::Base# A custom transiton that we want available across many AASM models.defcount_transitions!klass.class_evaldoaasm:with_klass=>CustomAASMBasedoafter_all_transitions:increment_transition_countendendend# A custom annotation that we want available across many AASM models.defrequires_guards!klass.class_evaldoattr_reader:authorizable_called,:transition_count,:fillable_calleddefauthorizable?@authorizable_called=trueenddeffillable?@fillable_called=trueenddefincrement_transition_count@transition_count ||= 0@transition_count += 1endendendendWhen 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.
classSimpleCustomExampleincludeAASM# Let's build an AASM state machine with our custom class.aasm:with_klass=>CustomAASMBasedorequires_guards!count_transitions!state:initialised,:initial=>truestate:filled_outstate:authorisedevent:fill_outdotransitions:from=>:initialised,:to=>:filled_out,:guard=>:fillable?endevent:authorisedotransitions:from=>:filled_out,:to=>:authorised,:guard=>:authorizable?endendendAASM comes with support for ActiveRecord and allows automatic persisting of the object's state in the database.
classJob < ActiveRecord::BaseincludeAASMaasmdo# default column: aasm_statestate:sleeping,:initial=>truestate:runningevent:rundotransitions:from=>:sleeping,:to=>:runningendevent:sleepdotransitions:from=>:running,:to=>:sleepingendendendYou can tell AASM to auto-save the object or leave it unsaved
job=Job.newjob.run# not savedjob.run!# saved# orjob.aasm.fire(:run)# not savedjob.aasm.fire!(:run)# savedSaving includes running all validations on the Job class. If
whiny_persistence flag is set to true, exception is raised in case of
failure. If whiny_persistence flag is set to false, methods with a bang return
true if the state transition is successful or false if an error occurs.
If you want make sure the state gets saved without running validations (and
thereby maybe persisting an invalid object state), simply tell AASM to skip the
validations. Be aware that when skipping validations, only the state column will
be updated in the database (just like ActiveRecord update_column is working).
classJob < ActiveRecord::BaseincludeAASMaasm:skip_validation_on_save=>truedostate:sleeping,:initial=>truestate:runningevent:rundotransitions:from=>:sleeping,:to=>:runningendevent:sleepdotransitions:from=>:running,:to=>:sleepingendendendIf you want to make sure that the AASM column for storing the state is not directly assigned, configure AASM to not allow direct assignment, like this:
classJob < ActiveRecord::BaseincludeAASMaasm:no_direct_assignment=>truedostate:sleeping,:initial=>truestate:runningevent:rundotransitions:from=>:sleeping,:to=>:runningendendendresulting in this:
job=Job.createjob.aasm_state# => 'sleeping'job.aasm_state=:running# => raises AASM::NoDirectAssignmentErrorjob.aasm_state# => 'sleeping'You can use enumerations in Rails 4.1+ for your state column:
classJob < ActiveRecord::BaseincludeAASMenumstate: {sleeping: 5,running: 99}aasm:column=>:state,:enum=>truedostate:sleeping,:initial=>truestate:runningendendYou can explicitly pass the name of the method which provides access
to the enumeration mapping as a value of enum, or you can simply
set it to true. In the latter case AASM will try to use
pluralized column name to access possible enum states.
Furthermore, if your column has integer type (which is normally the
case when you're working with Rails enums), you can omit :enum
setting --- AASM auto-detects this situation and enabled enum
support. If anything goes wrong, you can disable enum functionality
and fall back to the default behavior by setting :enum
to false.
AASM also supports Sequel besides ActiveRecord, and Mongoid.
classJob < Sequel::ModelincludeAASMaasmdo# default column: aasm_state
...
endendHowever it's not yet as feature complete as ActiveRecord. For example, there are scopes defined yet. See Automatic Scopes.
Since version 4.8.0AASM also supports Dynamoid as
persistence ORM.
AASM also supports persistence to Mongodb if you're using Mongoid. Make sure to include Mongoid::Document before you include AASM.
classJobincludeMongoid::DocumentincludeAASMfield:aasm_stateaasmdo
...
endendAASM also supports persistence to RethinkDB if you're using Nobrainer. Make sure to include NoBrainer::Document before you include AASM.
classJobincludeNoBrainer::DocumentincludeAASMfield:aasm_stateaasmdo
...
endendAASM also supports persistence in Redis via Redis::Objects. Make sure to include Redis::Objects before you include AASM. Note that non-bang events will work as bang events, persisting the changes on every call.
classUserincludeRedis::ObjectsincludeAASMaasmdoendendAASM will automatically create scope methods for each state in the model.
classJob < ActiveRecord::BaseincludeAASMaasmdostate:sleeping,:initial=>truestate:runningstate:cleaningenddefself.sleeping"This method name is already in use"endendclassJobsController < ApplicationControllerdefindex@running_jobs=Job.running@recent_cleaning_jobs=Job.cleaning.where('created_at >= ?',3.days.ago)# @sleeping_jobs = Job.sleeping #=> "This method name is already in use"endendIf you don't need scopes (or simply don't want them), disable their creation when
defining the AASM states, like this:
classJob < ActiveRecord::BaseincludeAASMaasm:create_scopes=>falsedostate:sleeping,:initial=>truestate:runningstate:cleaningendendSince version 3.0.13 AASM supports ActiveRecord transactions. So whenever a transition callback or the state update fails, all changes to any database record are rolled back. Mongodb does not support transactions.
There are currently 3 transactional callbacks that can be handled on the event, and 2 transactional callbacks for all events.
eventbefore_all_transactionseventbefore_transactioneventaasm_fire_event(withintransaction)eventafter_commit(ifeventsuccessful)eventafter_transactioneventafter_all_transactionsIf you want to make sure a depending action happens only after the transaction is committed,
use the after_commit callback along with the auto-save (bang) methods, like this:
classJob < ActiveRecord::BaseincludeAASMaasmdostate:sleeping,:initial=>truestate:runningevent:run,:after_commit=>:notify_about_running_jobdotransitions:from=>:sleeping,:to=>:runningendenddefnotify_about_running_job
...
endendjob=Job.where(state: 'sleeping').first!job.run!# Saves the model and triggers the after_commit callbackNote that the following will not run the after_commit callbacks because
the auto-save method is not used:
job=Job.where(state: 'sleeping').first!job.runjob.save!#notify_about_running_job is not runIf you want to encapsulate state changes within an own transaction, the behavior
of this nested transaction might be confusing. Take a look at
ActiveRecord Nested Transactions
if you want to know more about this. Nevertheless, AASM by default requires a new transaction
transaction(:requires_new => true). You can override this behavior by changing
the configuration
classJob < ActiveRecord::BaseincludeAASMaasm:requires_new_transaction=>falsedo
...
end
...
endwhich then leads to transaction(:requires_new => false), the Rails default.
Additionally, if you do not want any of your active record actions to be
wrapped in a transaction, you can specify the use_transactions flag. This can
be useful if you want want to persist things to the database that happen as a
result of a transaction or callback, even when some error occurs. The
use_transactions flag is true by default.
classJob < ActiveRecord::BaseincludeAASMaasm:use_transactions=>falsedo
...
end
...
endAASM supports Active Record pessimistic locking via with_lock for database persistence layers.
| Option | Purpose |
|---|---|
false (default) | No lock is obtained |
true | Obtain a blocking pessimistic lock e.g. FOR UPDATE |
| String | Obtain a lock based on the SQL string e.g. FOR UPDATE NOWAIT |
classJob < ActiveRecord::BaseincludeAASMaasm:requires_lock=>truedo
...
end
...
endclassJob < ActiveRecord::BaseincludeAASMaasm:requires_lock=>'FOR UPDATE NOWAIT'do
...
end
...
endAs a default AASM uses the column aasm_state to store the states. You can override
this by defining your favorite column name, using :column like this:
classJob < ActiveRecord::BaseincludeAASMaasm:column=>'my_state'do
...
endaasm:another_state_machine,column: 'second_state'do
...
endendWhatever column name is used, make sure to add a migration to provide this column
(of type string):
classAddJobState < ActiveRecord::Migrationdefself.upadd_column:jobs,:aasm_state,:stringenddefself.downremove_column:jobs,:aasm_stateendendAASM supports query methods for states and events
Given the following Job class:
classJobincludeAASMaasmdostate:sleeping,:initial=>truestate:running,:cleaningevent:rundotransitions:from=>:sleeping,:to=>:runningendevent:cleandotransitions:from=>:running,:to=>:cleaning,:guard=>:cleaning_needed?endevent:sleepdotransitions:from=>[:running,:cleaning],:to=>:sleepingendenddefcleaning_needed?falseendend# show all statesJob.aasm.states.map(&:name)#=> [:sleeping, :running, :cleaning]job=Job.new# show all permitted states (from initial state)job.aasm.states(:permitted=>true).map(&:name)#=> [:running]job.runjob.aasm.states(:permitted=>true).map(&:name)#=> [:sleeping]# show all non permitted statesjob.aasm.states(:permitted=>false).map(&:name)#=> [:cleaning]# show all possible (triggerable) events from the current statejob.aasm.events.map(&:name)#=> [:clean, :sleep]# show all permitted eventsjob.aasm.events(:permitted=>true).map(&:name)#=> [:sleep]# show all non permitted eventsjob.aasm.events(:permitted=>false).map(&:name)#=> [:clean]# show all possible events except a specific onejob.aasm.events(:reject=>:sleep).map(&:name)#=> [:clean]# list states for selectJob.aasm.states_for_select=>[["Sleeping","sleeping"],["Running","running"],["Cleaning","cleaning"]]# show permitted states with guard parameterjob.aasm.states({:permitted=>true},guard_parameter).map(&:name)Warnings are by default printed to STDERR. If you want to log those warnings to another output,
use
classJobincludeAASMaasm:logger=>Rails.loggerdo
...
endendYou can hide warnings by setting AASM::Configuration.hide_warnings = true
Now supports CodeDataQuery ! However I'm still in the process of submitting my compatibility updates to their repository. In the meantime you can use my fork, there may still be some minor issues but I intend to extensively use it myself, so fixes should come fast.
Warnings:
- Due to RubyMotion Proc's lack of 'source_location' method, it may be harder to find out the origin of a "cannot transition from" error. I would recommend using the 'instance method symbol / string' way whenever possible when defining guardians and callbacks.
AASM provides some matchers for RSpec: transition_from, have_state, allow_event and allow_transition_to. Add require 'aasm/rspec' to your spec_helper.rb file and use them like this:
# classes with only the default state machinejob=Job.newexpect(job).totransition_from(:sleeping).to(:running).on_event(:run)expect(job).not_totransition_from(:sleeping).to(:cleaning).on_event(:run)expect(job).tohave_state(:sleeping)expect(job).not_tohave_state(:running)expect(job).toallow_event:runexpect(job).to_notallow_event:cleanexpect(job).toallow_transition_to(:running)expect(job).to_notallow_transition_to(:cleaning)# on_event also accept argumentsexpect(job).totransition_from(:sleeping).to(:running).on_event(:run,:defragmentation)# classes with multiple state machinemultiple=SimpleMultipleExample.newexpect(multiple).totransition_from(:standing).to(:walking).on_event(:walk).on(:move)expect(multiple).to_nottransition_from(:standing).to(:running).on_event(:walk).on(:move)expect(multiple).tohave_state(:standing).on(:move)expect(multiple).not_tohave_state(:walking).on(:move)expect(multiple).toallow_event(:walk).on(:move)expect(multiple).to_notallow_event(:hold).on(:move)expect(multiple).toallow_transition_to(:walking).on(:move)expect(multiple).to_notallow_transition_to(:running).on(:move)expect(multiple).totransition_from(:sleeping).to(:processing).on_event(:start).on(:work)expect(multiple).to_nottransition_from(:sleeping).to(:sleeping).on_event(:start).on(:work)expect(multiple).tohave_state(:sleeping).on(:work)expect(multiple).not_tohave_state(:processing).on(:work)expect(multiple).toallow_event(:start).on(:move)expect(multiple).to_notallow_event(:stop).on(:move)expect(multiple).toallow_transition_to(:processing).on(:move)expect(multiple).to_notallow_transition_to(:sleeping).on(:move)# allow_event also accepts argumentsexpect(job).toallow_event(:run).with(:defragmentation)AASM provides assertions and rspec-like expectations for Minitest.
List of supported assertions: assert_have_state, refute_have_state, assert_transitions_from, refute_transitions_from, assert_event_allowed, refute_event_allowed, assert_transition_to_allowed, refute_transition_to_allowed.
Add require 'aasm/minitest' to your test_helper.rb file and use them like this:
# classes with only the default state machinejob=Job.newassert_transitions_fromjob,:sleeping,to: :running,on_event: :runrefute_transitions_fromjob,:sleeping,to: :cleaning,on_event: :runassert_have_statejob,:sleepingrefute_have_statejob,:runningassert_event_allowedjob,:runrefute_event_allowedjob,:cleanassert_transition_to_allowedjob,:runningrefute_transition_to_allowedjob,:cleaning# on_event also accept argumentsassert_transitions_fromjob,:sleeping,:defragmentation,to: :running,on_event: :run# classes with multiple state machinemultiple=SimpleMultipleExample.newassert_transitions_frommultiple,:standing,to: :walking,on_event: :walk,on: :moverefute_transitions_frommultiple,:standing,to: :running,on_event: :walk,on: :moveassert_have_statemultiple,:standing,on: :moverefute_have_statemultiple,:walking,on: :moveassert_event_allowedmultiple,:walk,on: :moverefute_event_allowedmultiple,:hold,on: :moveassert_transition_to_allowedmultiple,:walking,on: :moverefute_transition_to_allowedmultiple,:running,on: :moveassert_transitions_frommultiple,:sleeping,to: :processing,on_event: :start,on: :workrefute_transitions_frommultiple,:sleeping,to: :sleeping,on_event: :start,on: :workassert_have_statemultiple,:sleeping,on: :workrefute_have_statemultiple,:processing,on: :workassert_event_allowedmultiple,:start,on: :moverefute_event_allowedmultiple,:stop,on: :moveassert_transition_to_allowedmultiple,:processing,on: :moverefute_transition_to_allowedmultiple,:sleeping,on: :moveList of supported expectations: must_transition_from, wont_transition_from, must_have_state, wont_have_state, must_allow_event, wont_allow_event, must_allow_transition_to, wont_allow_transition_to.
Add require 'aasm/minitest_spec' to your test_helper.rb file and use them like this:
# classes with only the default state machinejob=Job.newjob.must_transition_from:sleeping,to: :running,on_event: :runjob.wont_transition_from:sleeping,to: :cleaning,on_event: :runjob.must_have_state:sleepingjob.wont_have_state:runningjob.must_allow_event:runjob.wont_allow_event:cleanjob.must_allow_transition_to:runningjob.wont_allow_transition_to:cleaning# on_event also accept argumentsjob.must_transition_from:sleeping,:defragmentation,to: :running,on_event: :run# classes with multiple state machinemultiple=SimpleMultipleExample.newmultiple.must_transition_from:standing,to: :walking,on_event: :walk,on: :movemultiple.wont_transition_from:standing,to: :running,on_event: :walk,on: :movemultiple.must_have_state:standing,on: :movemultiple.wont_have_state:walking,on: :movemultiple.must_allow_event:walk,on: :movemultiple.wont_allow_event:hold,on: :movemultiple.must_allow_transition_to:walking,on: :movemultiple.wont_allow_transition_to:running,on: :movemultiple.must_transition_from:sleeping,to: :processing,on_event: :start,on: :workmultiple.wont_transition_from:sleeping,to: :sleeping,on_event: :start,on: :workmultiple.must_have_state:sleeping,on: :workmultiple.wont_have_state:processing,on: :workmultiple.must_allow_event:start,on: :movemultiple.wont_allow_event:stop,on: :movemultiple.must_allow_transition_to:processing,on: :movemultiple.wont_allow_transition_to:sleeping,on: :move% gem install aasm# Gemfilegem'aasm'% rake build
% sudo gem install pkg/aasm-x.y.z.gemAfter installing AASM you can run generator:
% rails generate aasm NAME [COLUMN_NAME]Replace NAME with the Model name, COLUMN_NAME is optional(default is 'aasm_state'). This will create a model (if one does not exist) and configure it with aasm block. For Active record orm a migration file is added to add aasm state column to table.
Run test suite easily on docker
1. docker-compose build aasm
2. docker-compose run --rm aasm
Take a look at the CHANGELOG for details about recent changes to the current version.
Feel free to
- create an issue on GitHub
- ask a question on StackOverflow (tag with
aasm) - send us a tweet @aasm
- Scott Barron (2006–2009, original author)
- Travis Tilley (2009–2011)
- Thorsten Böttger (since 2011)
- Anil Maurya (since 2016)
This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose.
Copyright (c) 2006-2017 Scott Barron
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.