[Ruby] acts_as_state_machine question
Frederick Alger
fred at fredalger.net
Thu Nov 2 13:35:53 PST 2006
Does anyone actually use this Rails plugin? I'm finding
documentation, examples, and testability rather scant.
I'd love to hear if someone uses this *and* they can pass their unit
tests, because I'm stuck as a toad on a tire.
I've re-factored the order processing end of a Rails store I built to
use acts_as_state_machine to enforce workflow stages of an order, a
very simple transition table:
| -> confirmed -> shipped
placed -> |
| -> cancelled
In code:
=============
class Order < ActiveRecord::Base
acts_as_state_machine :initial => :new
state :new, :placed, :confirmed, :cancelled, :shipped
event :place do
transitions :from => :new, :to => :placed
end
event :confirm do
transitions :from => :placed, :to => :confirmed
end
event :cancel do
transitions :from => :placed, :to => :cancelled
end
event :ship do
transitions :from => :confirmed, :to => :shipped
end
#...
end
==============
Very simple, no? However, I'm having the damndest time getting my
unit tests to pass, because my Order objects have an initial state of
nil. When I create an Order from the console:
>> o = Order.new
=> #<Order:0x2684a74 @new_record=true ... >
>> o.state
=> nil
If I then fill that Order with valid data:
>> o.attributes = Order.find_first.attributes
>> o.state
=> nil
>> o.place!
NoMethodError: You have a nil object when you didn't expect it!
The error occured while evaluating nil.to_sym
/Users/fred/Sites/Store/config/../vendor/plugins/
acts_as_state_machine/lib/acts_as_state_machine.rb:146:in
`current_state'
/Users/fred/Sites/Store/config/../vendor/plugins/
acts_as_state_machine/lib/acts_as_state_machine.rb:89:in `next_states'
/Users/fred/Sites/Store/config/../vendor/plugins/
acts_as_state_machine/lib/acts_as_state_machine.rb:89:in `next_states'
/Users/fred/Sites/Store/config/../vendor/plugins/
acts_as_state_machine/lib/acts_as_state_machine.rb:93:in `fire'
/Users/fred/Sites/Store/config/../vendor/plugins/
acts_as_state_machine/lib/acts_as_state_machine.rb:201:in `place!'
acts_as_state_machine sets the initial state in before_create, so I
tried using Order.create instead of Order.new, with the same result.
Insights greatly appreciated,
- Fred Alger.
@: fred at fredalger.net
More information about the Ruby
mailing list