1
0

More than 1 year has passed since last update.

#Ruby の aasm gem で after_all_transitions の Callback が出来ない : AASM::UnknownStateMachineError のエラー

Last updated at Posted at 2019-11-07

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

問題

aasm do
end

の場合と

aasm(:some_name) do
end

の場合で callback の書き方が違う

解決


require 'aasm'

class Job
  include AASM

  aasm(:runner) do
    after_all_transitions :log_status_change

    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
  end

  def log_status_change
    puts "changing from #{aasm(:runner).from_state} to #{aasm(:runner).to_state} (event: #{aasm(:runner).current_event})"
    # changing from sleeping to running (event: run)

    # puts "changing from #{aasm.from_state} to #{aasm.to_state} (event: #{aasm.current_event})"
    # There is no state machine with the name 'default' defined in Job! (AASM::UnknownStateMachineError)
  end
end

job = Job.new
job.run

理由

aasm(:name) do
end

で複数の StateMachine を作ることができるが、それにフックさせる callback メソッドは aasm の DSLではなく フラットなメソッドとして書くため、どの種類の StateMachine かを教える必要があるっぽい

Original by Github issue

チャットメンバー募集

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

Twitter

1
0
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
1
0