Sha256: 1406723ef92be1c37c1afa81d34dfbdf461b140a6ccf949decf507b40cbcf62c

Contents?: true

Size: 885 Bytes

Versions: 26

Compression:

Stored size: 885 Bytes

Contents

# frozen_string_literal: true

# require 'bundler/setup'
# require 'polyphony'

require 'fiber'

class StateMachine < ::Fiber
  def initialize(state, rules)
    @state = state
    @rules = rules
    super() { |input| state_loop(input) }
  end

  attr_reader :state
  def state_loop(input)
    loop do
      @state = apply(input)
      input = Fiber.yield(@state)
    end
  end

  def apply(input)
    f = @rules[@state][input]
    return f.(@state) if f.is_a?(Proc)

    raise 'Invalid input'
  rescue => e
    @state
  end

  def transition(input)
    state = self.resume(input)
    # state.is_a?(Exception) ? (raise state) : state
  end
end

o = StateMachine.new(
  :off,
  {
    off: { turnon: ->(s) { :on } },
    on: { turnoff: ->(s) { :off } }
  }
)

loop do
  STDOUT << "#{o.state}: "
  input = gets.strip.to_sym
  # puts "  command: #{input.inspect}"
  o.transition(input)
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
polyphony-0.45.0 examples/core/xx-state-machine.rb
polyphony-0.44.0 examples/core/xx-state-machine.rb
polyphony-0.43.11 examples/core/xx-state-machine.rb
polyphony-0.43.10 examples/core/xx-state-machine.rb
polyphony-0.43.9 examples/core/xx-state-machine.rb
polyphony-0.43.8 examples/core/xx-state-machine.rb
polyphony-0.43.6 examples/core/xx-state-machine.rb
polyphony-0.43.5 examples/core/xx-state-machine.rb
polyphony-0.43.4 examples/core/xx-state-machine.rb
polyphony-0.43.3 examples/core/xx-state-machine.rb
polyphony-0.43.2 examples/core/xx-state-machine.rb
polyphony-0.43.1 examples/core/xx-state-machine.rb
polyphony-0.43 examples/core/xx-state-machine.rb
polyphony-0.42 examples/core/xx-state-machine.rb
polyphony-0.41 examples/core/xx-state-machine.rb
polyphony-0.40 examples/core/xx-state-machine.rb
polyphony-0.39 examples/core/xx-state-machine.rb
polyphony-0.38 examples/core/xx-state-machine.rb
polyphony-0.36 examples/core/xx-state-machine.rb
polyphony-0.34 examples/core/xx-state-machine.rb