Sha256: b70c55cd23b62cda46feb64de94bc2376cf344f64a0039662c598f64b83ea6d8

Contents?: true

Size: 697 Bytes

Versions: 1

Compression:

Stored size: 697 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 trigger event
    if trigger?(event)
      @state = transitions_for[event][@state]
      callbacks = @callbacks[@state] + @callbacks[:any]
      callbacks.each { |callback| callback.call }
      true
    end
  end

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
micromachine-0.0.11 lib/micromachine.rb