Sha256: e8a4f5d17983450fdc7591f56b53b3c21625bd6f62ff74c352bbbb90f2c0cf2a

Contents?: true

Size: 857 Bytes

Versions: 3

Compression:

Stored size: 857 Bytes

Contents

class MicroMachine
  InvalidEvent = Class.new(NoMethodError)

  attr :transitions_for
  attr :state

  def initialize initial_state
    @state = initial_state
    @transitions_for = Hash.new
    @callbacks = Hash.new { |hash, key| hash[key] = [] }
  end

  def on key, &block
    @callbacks[key] << block
  end

  def when(event, transitions)
    transitions_for[event] = transitions
  end

  def trigger event
    if trigger?(event)
      @state = transitions_for[event][@state]
      callbacks = @callbacks[@state] + @callbacks[:any]
      callbacks.each { |callback| callback.call }
      true
    else
      false
    end
  end

  def trigger?(event)
    transitions_for[event][state] ? true : false
  rescue NoMethodError
    raise InvalidEvent
  end

  def events
    transitions_for.keys
  end

  def ==(some_state)
    state == some_state
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
micromachine-1.0.3 lib/micromachine.rb
micromachine-1.0.2 lib/micromachine.rb
micromachine-1.0.1 lib/micromachine.rb