aasm的工作原理其实是状态机,与state_machine基本一致,关于state_machine的部分信息可以参考:http://flyingzl.javaeye.com/blog/362207
工作原理图:
以下内容转自:http://github.com/rubyist/aasm/tree/master
AASM - Ruby state machines
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.
AASM has the following features:
- States
- Machines
- Events
- Transitions
Download
The latest AASM can currently be pulled from the git repository on github.
Installation
From GitHub hosted gems
% sudo gem sources -a http://gems.github.com # (you only need to do this once) % sudo gem install rubyist-aasm
Building your own gems
% rake gem % sudo gem install pkg/aasm-2.1.gem
Simple Example
Here’s a quick example highlighting some of the features.
A Slightly More Complex Example
This example uses a few of the more complex features available.
当状态机建立好后,我们来探讨一下它的用法:
1、与数据库关联起来。
如上所示,我们通过aasm_column把状态机与数据库表的aasm_state字段关联起来,当我们调用状态机事件时,aasm_state的值会发生相应的变化。
2、可以定义状态机的初始状态(aasm_initial_state),当插入数据时,如果不干预状态机,它会自动获取一个初始状态(预先定义的),并保存到数据库表。
3、Model.even与Model.even!的区别。
先看以下代码:
If you call the bang! form of the transition event method, the state will persist.
So callingbook.close
will set the state toclosed
, but will not automatically save. Callingbook.close!
will set the
state *and* automatically save the AR object.
4、其它用法:
参考:http://github.com/rubyist/aasm/blob/dfc2874972daf601f3eeb4cd2bff589290cc2521/spec/unit/aasm_spec.rb
注意:
倘若状态机跳转不符合要求。如事件wakeup触发的状态是从sleeping到showering,working的,但如果调用wakeup时,状态机当前的状态不为sleeping时,
就会出现异常。所以对于这些异常要注意捕获和处理。