Created
February 5, 2017 05:01
-
-
Save kjlape/7304c36fcda8972a0ba417907af134ec to your computer and use it in GitHub Desktop.
State handler...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module StateHandlers | |
| class Base | |
| class_attribute :registered_states | |
| class_attribute :registered_events | |
| extended do | |
| registered_states = {} | |
| registered_events = Hash.new { |hash, key| hash[key] = { before: [], after: [] } } | |
| end | |
| def initialize(machine, attribute:) | |
| @machine = machine | |
| @state_attribute = attribute | |
| end | |
| def state | |
| registered_states[state_key].new(@machine) | |
| end | |
| def method_missing(method_name) | |
| registered_events[method_name][:before].each { |event| event.call(method_name, @machine) } | |
| state.public_send(method_name) | |
| registered_events[method_name][:after].each { |event| event.call(method_name, @machine) } | |
| end | |
| def self.register_state(klass) | |
| registered_states[klass.key] = klass | |
| end | |
| def self.register_event(event, hook = :after, callable, &block) | |
| registered_events[event][hook] << callable || block | |
| end | |
| private | |
| def state_key | |
| @machine.public_send(@state_attribute) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment