Sha256: bdef998a9ad4a88035b71f6f3feeeb26422a750bbad8a046e29634c8104165b4

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

module NxtStateMachine
  class State
    def initialize(enum, state_machine, **opts)
      @enum = enum
      @state_machine = state_machine
      @initial = opts.delete(:initial)
      @transitions = []
      @options = opts.with_indifferent_access
      @index = opts.fetch(:index)

      ensure_index_not_occupied
    end

    attr_accessor :enum, :initial, :index, :transitions, :state_machine, :options

    def to_s
      enum.to_s
    end

    def previous
      current_index = sorted_states.index { |state| state.index == index }
      sorted_states[(current_index - 1) % sorted_states.size]
    end

    def next
      current_index = sorted_states.index { |state| state.index == index }
      sorted_states[(current_index + 1) % sorted_states.size]
    end

    def last?
      sorted_states.last.index == index
    end

    def first?
      sorted_states.first.index == index
    end

    private

    def sorted_states
      state_machine.states.values.sort_by(&:index)
    end

    def ensure_index_not_occupied
      state_with_same_index = state_machine.states.values.find { |state| state.index == index }
      return unless state_with_same_index

      raise StateWithSameIndexAlreadyRegistered, "The index #{index} is already occupied by state: #{state_with_same_index.enum}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nxt_state_machine-0.1.2 lib/nxt_state_machine/state.rb