Module: Mongoid::StateMachine::ClassMethods

Defined in:
lib/mongoid/state_machine.rb

Instance Method Summary collapse

Instance Method Details

#event(event, opts = {}, &block) ⇒ Object

Define an event. This takes a block which describes all valid transitions for this event.

Example:

class Order

acts_as_state_machine :initial => :open

state :open
state :closed

event :close_order do
  transitions :to => :closed, :from => :open
end

end

transitions takes a hash where :to is the state to transition to and :from is a state (or Array of states) from which this event can be fired.

This creates an instance method used for firing the event. The method created is the name of the event followed by an exclamation point (!). Example: order.close_order!.



203
204
205
206
207
208
209
# File 'lib/mongoid/state_machine.rb', line 203

def event(event, opts={}, &block)
  tt = read_inheritable_attribute(:transition_table)

  e = SupportingClasses::Event.new(event, opts, tt, &block)
  write_inheritable_hash(:event_table, event.to_sym => e)
  define_method("#{event.to_s}!") { e.fire(self) }
end

#state(name, opts = {}) ⇒ Object

Define a state of the system. state can take an optional Proc object which will be executed every time the system transitions into that state. The proc will be passed the current object.

Example:

class Order

acts_as_state_machine :initial => :open

state :open
state :closed, Proc.new { |o| Mailer.send_notice(o) }

end



223
224
225
226
227
228
# File 'lib/mongoid/state_machine.rb', line 223

def state(name, opts={})
  state = SupportingClasses::State.new(name, opts)
  write_inheritable_hash(:states, state.value => state)

  define_method("#{state.name}?") { current_state.to_s == state.value }
end

#statesObject

Returns an array of all known states.



176
177
178
# File 'lib/mongoid/state_machine.rb', line 176

def states
  read_inheritable_attribute(:states).keys.collect { |state| state.to_sym }
end