5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASSMで状態管理

Posted at

インストール

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

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?