pluginaweek / state_machine

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

ordered states #330

Open neutralino1 opened 9 years ago

neutralino1 commented 9 years ago

Hi all,

If the states of your machine represent successive states instead of independent states (e.g. new -> pending -> ongoing -> completed), it is useful to know if a particular state has been passed. For example, if you want to know if a state has passed the pending state, you need to check if it is either ongoing or completed. This is not really maintainable if you have 10 or so states. The following pattern would be really useful.

model = Model.new
model.state > :ongoing
=> false
model.queue!
model.state > :new
=> true
model.start!
model.state > :pending
=> true

Is there currently a generic way to achieve this?

PhilT commented 9 years ago

I was looking for a way to do something similar too. Storing the states as numeric values in the database could be a way to do this. This would also allow you to order queries by progressive state. I saw someone mentioned it's possible to store states as enums in PostgreSQL using the Statesman gem.

I'm about to investigate this myself. However, I'm not too keen on the Statesman gem as a whole and may come back to state_machine but I'm worried about a lack of a maintainer.

PhilT commented 9 years ago

Maybe you could implement this in your model with something like:

model.past(:ongoing)

And put the states in an array and do states.index(self.state) > states.index(state)