🖥

#Ruby の aasm で すべてのイベントに callback で共通処理を挟んでログ出力したりするには after_all_tran

2019/11/06に公開

ほぼREADMEのまま

aasm/aasm: AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid)

require 'aasm'

class Job
  include AASM

  aasm do
    state :sleeping, initial: true
    state :running, :cleaning

    event :run do
      transitions from: :sleeping, to: :running
    end

    event :clean do
      transitions from: :running, to: :cleaning
    end

    event :sleep do
      transitions from: [:running, :cleaning], to: :sleeping
    end

    after_all_transitions :log_status_change
  end

  def log_status_change
    puts "changing from #{aasm.from_state} to #{aasm.to_state} (event: #{aasm.current_event})"
  end
end
job = Job.new
# => #<Job:0x00007fb0d9f80750>

job.run
# changing from sleeping to running (event: run)

job.sleep
# changing from running to sleeping (event: sleep)

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2674

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-11-06

Discussion