piotrmurach/finite_machine

HIGH_PRIORITY_ANY_STATE and HIGH_PRIORITY_ANY_EVENT

dmgr opened this issue · 2 comments

dmgr commented

I needed a general callbacks to be fired before specific ones, so I created a monkey patch to specify high priority any event/state:

HIGH_PRIORITY_ANY_EVENT = :high_priority_any_event
HIGH_PRIORITY_ANY_STATE = :high_priority_any_state

  def trigger(event, *args, &block)
      sync_exclusive do
        [event.type].each do |event_type|
          [HIGH_PRIORITY_ANY_STATE, HIGH_PRIORITY_ANY_EVENT, event.name, ANY_STATE, ANY_EVENT].each do |event_name|
            hooks.call(event_type, event_name) do |hook|
              handle_callback(hook, event)
              off(event_type, event_name, &hook) if hook.is_a?(Once)
            end
          end
        end
      end
    end

and I am using it like that:

on_enter :high_priority_any_state do |event|
end

It would be nice if I could specify a priority for callbacks, for example the default priority could be 0, and if I would like to "general" callback to be fired before "specific" one I could do something like:

on_enter priority: 1 do |event|
end

or to be more explicit

on_enter :any, priority: 1 do |event|
end

Hi. Just reading other issue posts. I have a question about this one. Looking at the doc's for the callback sequence:
https://github.com/peter-murach/finite_machine#57-execution-sequence

Are you saying that you wanted the on_enter called before on_enter :yellow?
How is it that neither on_before nor on_transition did the trick for you?

Pardon the kibitzing.

@dmgr I've changed the default order to fire general callbacks before event/state specific ones. I believe this is a more 'natural' way to think about it. I don't believe there is any need for specifying priority as it would greatly increase complexity and probably be superfluous for a lot of situations. I will release this shortly as part of v0.12.0.