Method: StateMachine::State#initialize

Defined in:
lib/state_machine/state.rb

#initialize(machine, name, options = {}) ⇒ State

Creates a new state within the context of the given machine.

Configuration options:

  • :initial - Whether this state is the beginning state for the machine. Default is false.

  • :value - The value to store when an object transitions to this state. Default is the name (stringified).

  • :cache - If a dynamic value (via a lambda block) is being used, then setting this to true will cache the evaluated result

  • :if - Determines whether a value matches this state (e.g. :value => lambda Time.now, :if => lambda {|state| !state.nil?}). By default, the configured value is matched.

  • :human_name - The human-readable version of this state’s name



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/state_machine/state.rb', line 57

def initialize(machine, name, options = {}) #:nodoc:
  assert_valid_keys(options, :initial, :value, :cache, :if, :human_name)
  
  @machine = machine
  @name = name
  @qualified_name = name && machine.namespace ? :"#{machine.namespace}_#{name}" : name
  @human_name = options[:human_name] || (@name ? @name.to_s.tr('_', ' ') : 'nil')
  @value = options.include?(:value) ? options[:value] : name && name.to_s
  @cache = options[:cache]
  @matcher = options[:if]
  @initial = options[:initial] == true
  @context = StateContext.new(self)
  
  if name
    conflicting_machines = machine.owner_class.state_machines.select {|other_name, other_machine| other_machine != machine && other_machine.states[qualified_name, :qualified_name]}
    
    # Output a warning if another machine has a conflicting qualified name
    # for a different attribute
    if conflict = conflicting_machines.detect {|other_name, other_machine| other_machine.attribute != machine.attribute}
      name, other_machine = conflict
      warn "State #{qualified_name.inspect} for #{machine.name.inspect} is already defined in #{other_machine.name.inspect}"
    elsif conflicting_machines.empty?
      # Only bother adding predicates when another machine for the same
      # attribute hasn't already done so
      add_predicate
    end
  end
end