state_machine

Defining

  • state_machine creates a new machine with the given name
  • The default name, if not specified, is :state

Options

:attribute
  • Name of the attribute to store the state value in
  • Default: name of the machine
:initial
  • The initial state of the attribute
  • Can be a static state or a lambda block which will be evaluated at runtime (e.g. lambda {|vehicle| vehicle.speed### 0 ? :parked : :idling})
  • Default: nil
:initialize
  • Whether to automatically initialize the attribute by hooking into #initialize on the owner class
  • Default: true.
:action
  • The instance method to invoke when an object transitions
  • Default: nil unless otherwise specified by the configured integration
:namespace
  • The name used for namespacing all generated state / event instance methods (e.g. "heater" would generate :turn_on_heater and :turn_off_heater for the :turn_on/:turn_off events).
  • Default: nil
:integration
  • The name of the integration to use for adding library-specific behavior to the machine
  • Default: Determined automatically.
:plural

The pluralized version of the name. By default, this will attempt to call pluralize on the name. If this method is not available, an "s" is appended. This is used for generating scopes.

:messages
  • The error messages to use when invalidating objects due to failed transitions.
  • Messages include:
    • :invalid
    • :invalid_event
    • :invalid_transition
:use_transactions
  • Whether transactions should be used when firing events
  • Default: true

Block

  • Used to configure the states, events and transitions for the state machine.
  • Executed within the context of the state machine so you will not be able to access any class methods unless you refer to them directly (i.e. specifying the class name)
Examples

With the default name/attribute and no configuration:

    state_machine do
      event :park do
        ...
      end
    end

The above example will define a state machine named state that will store the value in the state attribute. Every vehicle will start without an initial state.

With a custom name / attribute:

  class Vehicle
    state_machine :status, :attribute => :status_value do
      ...
    end
  end

With a static initial state:

  class Vehicle
    state_machine :status, :initial => :parked do
      ...
    end
  end

With a dynamic initial state:

  class Vehicle
    state_machine :status, :initial => lambda {|vehicle| vehicle.speed### 0 ? :parked : :idling} do
      ...
    end
  end

results matching ""

    No results matching ""