インストール
Gemfile
gem 'aasm'
bundle install
モデル
ファイルをダウンロードして別の箇所にアップロードするための情報を管理する感じ。
class DownloadFile < ActiveRecord::Base
include AASM
attr_accessible :status, :uri
# 状態を保存する列
# 列の型はstringにしないとダメ
aasm_column :status
# 使用する状態
aasm_state :not_donwloaded
aasm_state :downloaded
aasm_state :uploaded
# 初期状態
aasm_initial_state :not_donwloaded
# シンボルで指定した名前のメソッドが定義される
aasm_event :downloaded do
# このメソッドが実行されるとstatusがdownloadedになる
# 元の状態がnot_downloadedでない場合、例外が発生する
transitions to: :downloaded, from: :not_donwloaded
end
aasm_event :uploaded do
transitions to: :uploaded, from: :downloaded
end
# 状態を確認するためのメソッド群
def not_downloaded?
true if self.status == :not_donwloaded.to_s
end
def downloaded?
true if self.status == :downloaded.to_s
end
def uploaded?
true if self.status == :uploaded.to_s
end
end
使い方
file = DownloadFile.create(uri: "hogehoge")
p file.not_downloaded? # => true
file.downloaded
p file.downloaded? # => true
file.uploaded
p file.uploaded? # => true
参考
http://memo.yomukaku.net/entries/228
http://techblog.heartrails.com/2011/02/rails-aasm.html