lib/finite_machine/dsl.rb in finite_machine-0.4.0 vs lib/finite_machine/dsl.rb in finite_machine-0.5.0
- old
+ new
@@ -10,11 +10,17 @@
attr_accessor :top_level
end
attr_threadsafe :machine
- def initialize(machine)
+ attr_threadsafe :attrs
+
+ # Initialize a generic DSL
+ #
+ # @api public
+ def initialize(machine, attrs = {})
+ self.attrs = attrs
self.machine = machine
end
def method_missing(method_name, *args, &block)
if @machine.respond_to?(method_name)
@@ -28,22 +34,25 @@
sync_exclusive { instance_eval(&block) }
# top_level.instance_eval(&block)
end
end # GenericDSL
+ # A class responsible for adding state machine specific dsl
class DSL < GenericDSL
attr_threadsafe :defer
attr_threadsafe :initial_event
# Initialize top level DSL
#
# @api public
- def initialize(machine)
- super(machine)
+ def initialize(machine, attrs = {})
+ super(machine, attrs)
machine.state = FiniteMachine::DEFAULT_STATE
- self.defer = true
+ self.defer = true
+
+ initialize_attrs
end
# Define initial state
#
# @example
@@ -57,39 +66,57 @@
# @return [StateMachine]
#
# @api public
def initial(value)
state, name, self.defer = parse(value)
- machine.state = state unless defer
+ unless defer
+ machine.state = state
+ machine.initial_state = state
+ end
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
- # to initiate events in the context of a particular object.
+ # Attach state machine to an object
#
+ # This allows state machine to initiate events in the context
+ # of a particular object
+ #
+ # @example
+ # FiniteMachine.define do
+ # target :red
+ # end
+ #
# @param [Object] object
#
+ # @return [FiniteMachine::StateMachine]
+ #
# @api public
- def target(object)
- machine.env.target = object
+ def target(object = nil)
+ if object.nil?
+ machine.env.target
+ else
+ machine.env.target = object
+ end
end
# Define terminal state
#
# @example
# terminal :red
#
- # @return [StateMachine]
+ # @return [FiniteMachine::StateMachine]
#
# @api public
def terminal(value)
machine.final_state = value
end
# Define state machine events
#
+ # @return [FiniteMachine::StateMachine]
+ #
# @api public
def events(&block)
machine.events.call(&block)
end
@@ -106,9 +133,18 @@
def handlers(&block)
machine.errors.call(&block)
end
private
+
+ # Initialize state machine properties based off attributes
+ #
+ # @api private
+ def initialize_attrs
+ attrs[:initial] and initial(attrs[:initial])
+ attrs[:target] and target(attrs[:target])
+ attrs[:terminal] and terminal(attrs[:terminal])
+ end
# Parse initial options
#
# @param [Object] value
#