State machines
or
how to elegantly code changes to your models

Everybody has state
- some entries in the DB
- CRUD on them
Getting fancy
- callbacks: before_save, etc.
- why?
Have u ever seen the magic field?
- STATE
- or other variations...
Issues
- what values can state have => enum
- do I just update the state?
- maybe u can put some callbacks
- when u update the state, u gotta update something else as well => find & replace
- can u update it with any possible value?
- the new guys comes in and doesn't know "conventions"
Alternative: state machines
- alias: finite state machine, finite automaton, etc.
- current state
- transitions

Hands on
Alternatives
state_machine
- exactly the same, but with some bugs
- https://github.com/pluginaweek/state_machine/issues/251
- no longer maintained
aasm
- kinda the same
- one weird thing:
- normal methods don't save
- bang methods save
- normal functionality is with exceptions
- can be disabled on state machine level
- more fine grained transaction control
and others
- workflow
- ruote
- transitions
Gotchas
- not a silver bullet
- keep them simple (as simple as possible)
- can lead to hard to read code (same as with save callbacks)
Service Objects
- encapsulate everything about a transition
- controlled order of things
- write a lot of code
- gotta decide if it's worth it
?
Thanks
How do you handle state?
By Horia Radu
How do you handle state?
- 279