piotrmurach / finite_machine

A minimal finite state machine with a straightforward syntax.
https://piotrmurach.github.io/finite_machine/
MIT License
808 stars 38 forks source link

state machines definition inheritance #32

Closed dmgr closed 9 years ago

dmgr commented 9 years ago

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 9 years ago

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
piotrmurach commented 9 years ago

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!

piotrmurach commented 9 years ago

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