Ruby State Machine - 动态初始状态

时间:2014-05-06 01:20:06

标签: ruby state-machine

我制作了一台状态机来确定动态初始状态dormantseeking_flesh。我在运行RSpec后收到以下错误:

Failure/Error: @titan = Titan.new('Abnormal', 8, false)
IndexError:
  :dormant is an invalid name

究竟是什么导致此错误,我该如何解决?

规格:

describe '#state' do
  before do
    @titan = Titan.new('Abnormal', 8, false)
  end

  it 'should be dormant' do
    expect(@titan.state).to eq('dormant')
  end
end

生产:

require 'state_machine'

class Titan
  def initialize(type, meters, active)
    @type = type
    @meters = meters
    @active = active
    super()
  end

  state_machine :state, initial: ->(titan) { titan.active? ? :seeking_flesh : :dormant } do
    # just enough to pass...
  end

  def active?
    current_hour = Time.now.hour
    if current_hour <= 19 && current_hour >= 5
      @time = true
    end
  end
end

1 个答案:

答案 0 :(得分:1)

声明动态状态时,必须声明所有状态。这也允许你开始考虑Titan或你的对象可能参与的任何其他状态。另外,如果你正在使用rubocop,那么对于任何坚持使用它的人来说,这遵循新的1.9 lambda语法。

解决方案:

state_machine :state, initial: ->(t) { t.active? ? :seeking_flesh : :dormant } do
  state :dormant, :seeking_flesh, :attacking # this must be present
end