state-machines / state_machines

Adds support for creating state machines for attributes on any Ruby class
https://github.com/state-machines/state_machines
MIT License
814 stars 91 forks source link

Multiple initial states #42

Closed samstickland closed 8 years ago

samstickland commented 8 years ago

Hi,

It is possible to have multiple initial states? I'd like a statement machine to work like this:

unsubmitted -> pending_approval -> approved

with events submit and approve that move between these three states

But I'd also like to have a state called 'template'. For an object created with state template it should not be able to transition to any other state. I'd happy to explicitly state the desired initial state at creation.

I attempted something like this, but it didn't work:

  state_machine :state, initial: [:unsubmitted, :template] do
    event :submit do
      transition :unsubmitted => :pending_approval
    end

    event :approve do
      transition :pending_approval => :approved
    end

Is this possible? I'd rather not do this, as I need to create a 'template' object atomically.

  state_machine :state, initial: :unsubmitted do
    event :submit do
      transition :unsubmitted => :pending_approval
    end

    event :approve do
      transition :pending_approval => :approved
    end

    event :make_template do
      transition :unsubmitted => :template
    end
  end

Although, that said, perhaps the event only needs to exist to make the state machine aware of the state, and I can do this in ActiveRecord: MyObject.create!(state: :template, ...) and it's good enough.

samstickland commented 8 years ago

Ah, OK I found I can do this:

  state_machine :state, initial: :unsubmitted do
    state :template

    event :submit do
      transition :unsubmitted => :pending_approval
    end

    event :approve do
      transition :pending_approval => :approved
    end
  end

I thought I'd tried this and it didn't work, but the error was in my test suite.