class FiniteMachine::StateParser
A class responsible for converting transition arguments to states
Used by {TransitionBuilder} to parse user input state transitions.
@api private
Constants
- NON_STATE_KEYS
- STATE_KEYS
Public Class Methods
Extract states from user defined attributes
@example
StateParser.parse({from: [:green, :blue], to: :red}) # => {green: :red, green: :blue}
@param [Proc] block
@yield [Hash] the resolved states
@return [Hash] the resolved states
@api public
# File lib/finite_machine/state_parser.rb, line 27 def self.parse(attributes, &block) attrs = ensure_only_states!(attributes) states = extract_states(attrs) block ? states.each(&block) : states end
Private Class Methods
Check if attributes contain :from or :to key
@example
StateParser.contains_from_to_keys?({from: :green, to: :red}) # => true
@example
StateParser.contains_from_to_keys?({:green => :red}) # => false
@return [Boolean]
@api public
# File lib/finite_machine/state_parser.rb, line 73 def self.contains_from_to_keys?(attrs) STATE_KEYS.any? { |key| attrs.keys.include?(key) } end
Convert collapsed attributes to states hash
@example
StateParser.convert_attributes_to_states_hash([:green, :red] => :yellow) # => {green: :yellow, red: :yellow}
@param [Hash] attrs
the attributes to convert to a simple hash
@return [Hash]
@api private
# File lib/finite_machine/state_parser.rb, line 102 def self.convert_attributes_to_states_hash(attrs) attrs.each_with_object({}) do |(k, v), hash| if k.respond_to?(:to_ary) k.each { |el| hash[el] = v } else hash[k] = v end end end
Convert attrbiutes with :from, :to keys to states hash
@return [Hash]
@api private
# File lib/finite_machine/state_parser.rb, line 83 def self.convert_from_to_attributes_to_states_hash(attrs) Array(attrs[:from] || ANY_STATE).each_with_object({}) do |state, hash| hash[state] = attrs[:to] || state end end
Extract only states from attributes
@return [Hash]
@api private
# File lib/finite_machine/state_parser.rb, line 38 def self.ensure_only_states!(attrs) attributes = attrs.dup NON_STATE_KEYS.each { |key| attributes.delete(key) } raise_not_enough_transitions unless attributes.any? attributes end
Perform extraction of states from user supplied definitions
@return [Hash] the resolved states
@api private
# File lib/finite_machine/state_parser.rb, line 51 def self.extract_states(attrs) if contains_from_to_keys?(attrs) convert_from_to_attributes_to_states_hash(attrs) else convert_attributes_to_states_hash(attrs) end end
Raise error when not enough transitions are provided
@raise [NotEnoughTransitionsError]
if the event has no transitions
@return [nil]
@api private
# File lib/finite_machine/state_parser.rb, line 121 def self.raise_not_enough_transitions raise NotEnoughTransitionsError, "please provide state transitions" end