Hey all, I found a useful application of a state machine that relates to connections between two objects. A perfect example is friendship (like Facebook friends).
- If you send someone a friend request, you are waiting for them to accept
your state: inactive => sent_request
their state: inactive => pending_request
- If they accept the request
your state: sent_request => active
their state: pending_request => active
This allows me to have complex behavior for the friendship model. For example, you could add blocking pretty easily. You could allow two users who send each other friend requests to automatically become friends.
Here is some sample code:https://gist.github.com/venkatd/f1e6345a183f10367436
For every "friendship" relationship between two users, there will be two rows in the database. We will represent the two way relationship with two one-way relationships. The main thing I'm noticing is that some states are inverses of each other.
For example. sent_request is the inverse of pending_request, other_blocked is the inverse of blocked.
Some have the same inverses. For example, the inverse of active is active. (If A is friends with B it means B is also friends with A)
Anyone have any ideas on how to generalize this? I think state_machine has some really interesting applications for connections between objects.
Here are some interesting applications:
- Following/follower model
- Friend request model
- Favorites (user <=> post relationship)
- Flag as spam
When it comes down to it, I think you just need to specify the following:
- model A
- model B
- which states are inverses of each other
- the state_machine transitions (I manually wrote out the inverse events but they can be generated automatically by applying the inverses)
- the initial states