Sha256: 5c3ab01557eeea0dbacac7b159586d8afac8df70493d16934679e3f4f09d040c

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

module Mutator
  class Machine
    attr_reader :stateholder

    def initialize stateholder
      @stateholder = stateholder
    end

    def valid?
      self.class.states.include? current_state
    end

    def current_state
      stateholder.state
    end

    def transition options
      options = extract options
      transition, success, failure = options.values

      if transition.call
        success.call transition
        true
      else
        failure.call transition
        false
      end
    end

    def self.states
      transitions.map do |transition|
        to, from = transition[:to], transition[:from]
        [to, from]
      end.flatten.uniq
    end

    def states
      self.class.states
    end

    def transitions
      self.class.transitions
    end

  protected

    def extract options
      to = options.fetch(:to)

      {
        transition: Transition.new(to: to, from: current_state, machine: self),
        success: lambda { |_| },
        failure: lambda { |_| }
      }.merge options
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mutator-0.2.0 lib/mutator/machine.rb