pluginaweek / state_machine

Adds support for creating state machines for attributes on any Ruby class
http://www.pluginaweek.org
MIT License
3.74k stars 507 forks source link

Generic guards #267

Open sporto opened 11 years ago

sporto commented 11 years ago

At the moment I am doing something like this:

event :fulfill do
    transition [:new, :paid] => :fulfilled, :if => :can_transition?
end

event :pay do
    transition [:new, :fulfilled] => :paid, :if => :can_transition?
end

event :close do
    transition [:fulfilled, :paid] => :closed, :if => :can_transition?
end

:if => :can_transition? is repeated in every transition declaration which make the code harder to maintain.

Maybe there is a way already that I don't know of but it would be really nice if there was a way of defining generic guards, instead of this repetition.

Similar to this request https://groups.google.com/forum/#!searchin/pluginaweek-talk/condition/pluginaweek-talk/KwE8g1OKXZg/70driFcCLG8J

the8472 commented 11 years ago

If you don't need the fluffy can_fulfill? etc. instance methods you could just write a before_transition any => all handler that returns false if the condition is not fulfilled.

sporto commented 11 years ago

@the8472 thanks, but this doesn't seem to work, I tried returning false in a before_transition filter but the transition still happens. It seems like before_transition has no relevance to wherever the transition should proceed.

the8472 commented 11 years ago

I thought returning false does work. But the documentation says throw :halt, so try that

the8472 commented 11 years ago

Ah, it depends on the integration, default is the throw, but you can configure another one, such as the AR-integration does: http://rdoc.info/github/pluginaweek/state_machine/master/StateMachine/Callback:terminator

sporto commented 11 years ago

@the8472, thanks throw :halt works. Still it would be nice to have something that works with the predicate methods, .can_pay?