piotrmurach/finite_machine

state machines definition inheritance

dmgr opened this issue · 3 comments

dmgr commented

Why inherited state machines doesn't inherit callbacks and what can be done to fix it?

For example SpecificStateMachine that inherits from GenericStateMachine doesn't inherit "on_enter" callback:

  class GenericStateMachine < FiniteMachine::Definition
    callbacks do
      on_enter do |event|
        target.state = event.to
      end
    end
  end

  class SpecificStateMachine < GenericStateMachine
    callbacks do
      on_after :accept do |event|
        #TODO
      end
    end
  end
dmgr commented

I found a workaround, but first snippet was intuitive and logical IMO:

  class GenericStateMachine < FiniteMachine::Definition
    def self.inherited subclass
      subclass.callbacks do
        on_enter do |event|
          target.state = event.to
        end
      end

      super
    end
  end

The FiniteMachine::Definition is just sugar for the define method. It decoares the class with class instance methods and thus doesn't really provide inheritance as such but a more conveninent way to factor state machine instances. I'm thinking it should probably be rewritten to module to better express what it does. I find your example interesting. Could you provide more background why such inheritane would be useful? More code would be even better, would you mind provided a fuller example? I haven't had any need thus far to use the inheritance but I'm more than happy to work with you on this!

@dmgr I've implemented definition inheritance. Your initial example should work like a charm now.