state_machine gem如何使用transition_for

时间:2013-11-21 13:56:49

标签: ruby state-machine

我想使用state_machine gem的transition_for,但文档没有显示我应该使用哪个对象:

http://rdoc.info/github/pluginaweek/state_machine/master/StateMachine/Event:transition_for

你有一个例子可以告诉我吗?

1 个答案:

答案 0 :(得分:1)

class Stately
  state_machine :state, initial: :pending do
    state :approved
    state :declined

    event :approve do
      transition pending: :approved
    end

    event :decline do
      transition all => :declined
    end
  end
end

stately = Stately.new
stately.state
#=> :pending

stately.state_events
#=> [ :approve, :decline ]

stately.approve
stately.state_events
#=> [ :decline ]

如果您想要做的是防止自己意外触发会引发异常的事件(比试图查看所有事件的范围窄得多),那么您也可以这样做......

stately = Stately.new
stately.state
#=> :pending

stately.can_approve?
#=> true
stately.can_decline?
#=> true

stately.approve
stately.can_approve?
#=> false
stately.can_decline?
#=> true