state-machines / state_machines

Adds support for creating state machines for attributes on any Ruby class
https://github.com/state-machines/state_machines
MIT License
814 stars 91 forks source link

fire_state_event! #66

Open gagalago opened 6 years ago

gagalago commented 6 years ago

I can't find the bang version of fire_state_event (throw error instead of returning false). What is the best way to add this feature?

oehlschl commented 6 years ago

We've been using the following pattern:

# for state machine on attribute 'status' and some event_name
my_model.update_attributes!(status_event: event_name)

This raises an exception, essentially triggering the bang version of the event. Apparently this may be part of the ActiveRecord extension, though: https://github.com/state-machines/state_machines/issues/36 (very dated, but result of a quick search)

Hope this helps.

oehlschl commented 6 years ago

Still looking for the implementation, but there's some documentation here: https://github.com/pluginaweek/state_machine#explicit-vs-implicit-event-transitions

oehlschl commented 6 years ago

Found the implementation of implicit / attribute-based state transitions here: https://github.com/state-machines/state_machines/blob/c94d6908ff2a005604da60bb51f0f41187e006bb/lib/state_machines/machine.rb#L1051-L1051

It looks like there are some caveats with implicit transitions documented elsewhere: https://github.com/state-machines/state_machines/blob/c94d6908ff2a005604da60bb51f0f41187e006bb/lib/state_machines/machine.rb#L1204-L1204

I didn't see any support for passing arguments (ex: an attribute like state_event_arguments), and adding this as an additional attribute seems messy.

Therefore I would also be in favor of defining a .fire!() method, possibly via a special argument to .fire(), and rewriting Event.add_actions to leverage that instead: https://github.com/state-machines/state_machines/blob/a8e18f614d81c024437a87f12f091e6b0c62a5f8/lib/state_machines/event.rb#L224-L224