状态机/状态机-转换中的下一个状态

问题描述 投票:2回答:1

我正在使用https://github.com/state-machines/state_machines for Rails在对象状态改变之前和之后存储和完成工作。

我想做的是有一个单一的方法,对于给定的一组before_transition,可以在events中调用,而对于给定的event,则具有before_transition所调用的方法有点不同。

例如,说该方法称为log_state_change,类似:

def log_state_change
  case <???>
  when "successful"
    Rails.logger.info "Successful"
  when "failure"
    Rails.logger.info "Failure"
  when "starting_run"
    Rails.logger.info "Starting run" 
  else
    Rails.logger.error "Unknown"
end

我找不到适合以上<???>的方法。也许更熟悉此宝石的人可以提供帮助?

ruby-on-rails ruby state-machine
1个回答
0
投票

您可以在before_transition回调中接受参数,并获取实现预期行为所需的所有数据。

传递您可以在the source code of the library找到的参数的代码。您也可以使用around_transition来实现此逻辑。

require 'state_machines'

class Light

  state_machine :state, initial: :off do

    before_transition from: any, do: :log_me

    event :light do
      transition all => :on
    end

    event :dark do
      transition [:on] => :off
    end

  end

  def log_me(transition)
    case transition.event
    when :light
      p "`light` event was called to transition from #{transition.from} to #{transition.to}"
    when :dark
      p "`dark` event was called to transition from #{transition.from} to #{transition.to}"
    else
      p "`#{transition.event}` was called to transition from #{transition.from} to #{transition.to}"
    end
  end
end

a = Light.new

a.light # => "`light` event was called to transition from off to on"
a.dark # => "`dark` event was called to transition from on to off"
© www.soinside.com 2019 - 2024. All rights reserved.