ROR汇集---aasm

本文详细介绍了AASM状态机的工作原理及其在Ruby类中的应用。包括如何定义状态、事件及转换,并展示了如何将状态机与数据库字段关联,以及一些高级特性和使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 calling book.close will set the state to closed, but will not automatically save. Calling book.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时,
就会出现异常。所以对于这些异常要注意捕获和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值