lib/finite_machine/dsl.rb in finite_machine-0.3.0 vs lib/finite_machine/dsl.rb in finite_machine-0.4.0
- old
+ new
@@ -1,9 +1,8 @@
# encoding: utf-8
module FiniteMachine
-
# A generic DSL for describing the state machine
class GenericDSL
include Threadable
class << self
@@ -30,11 +29,10 @@
# top_level.instance_eval(&block)
end
end # GenericDSL
class DSL < GenericDSL
-
attr_threadsafe :defer
attr_threadsafe :initial_event
# Initialize top level DSL
@@ -46,16 +44,24 @@
self.defer = true
end
# Define initial state
#
+ # @example
+ # initial :green
+ #
+ # @example
+ # initial state: green, defer: true
+ #
# @param [String, Hash] value
#
+ # @return [StateMachine]
+ #
# @api public
def initial(value)
state, name, self.defer = parse(value)
- self.initial_event = name
+ machine.state = state unless defer
event = proc { event name, from: FiniteMachine::DEFAULT_STATE, to: state }
machine.events.call(&event)
end
# Attach state machine to an object. This allows state machine
@@ -68,10 +74,15 @@
machine.env.target = object
end
# Define terminal state
#
+ # @example
+ # terminal :red
+ #
+ # @return [StateMachine]
+ #
# @api public
def terminal(value)
machine.final_state = value
end
@@ -98,23 +109,32 @@
private
# Parse initial options
#
- # @param [String, Hash] value
+ # @param [Object] value
#
# @return [Array[Symbol,String]]
#
# @api private
def parse(value)
- if value.is_a?(String) || value.is_a?(Symbol)
+ unless value.is_a?(Hash)
[value, FiniteMachine::DEFAULT_EVENT_NAME, false]
else
- [value[:state], value.fetch(:event, FiniteMachine::DEFAULT_EVENT_NAME),
- !!value[:defer]]
+ [value.fetch(:state) { raise_missing_state },
+ value.fetch(:event) { FiniteMachine::DEFAULT_EVENT_NAME },
+ value.fetch(:defer) { false }]
end
end
+
+ # Raises missing state error
+ #
+ # @api private
+ def raise_missing_state
+ raise MissingInitialStateError,
+ 'Provide state to transition :to for the initial event'
+ end
end # DSL
class EventsDSL < GenericDSL
# Create event and associate transition
@@ -149,8 +169,7 @@
#
# @api public
def handle(*exceptions, &block)
machine.handle(*exceptions, &block)
end
-
end # ErrorsDSL
end # FiniteMachine