1
0
Fork 0
mirror of https://github.com/aasm/aasm synced 2023-03-27 23:22:41 -04:00
aasm/lib/aasm/state_machine.rb
Tyler Hogan 77cd065eeb Deep clone state machine during inheritance (with tests) (#429)
* Deep clone state machine during inheritance.
Allows child classes to extend the parent state machine without modifying the parents state machine.

* Add tests

* Also need to clone global callbacks to support inheritance

* Added tests to ensure parent is not changed in inheritance
2017-03-08 12:28:27 +05:30

53 lines
1.5 KiB
Ruby

module AASM
class StateMachine
# the following four methods provide the storage of all state machines
attr_accessor :states, :events, :initial_state, :config, :name, :global_callbacks
def initialize(name)
@initial_state = nil
@states = []
@events = {}
@global_callbacks = {}
@config = AASM::Configuration.new
@name = name
end
# called internally by Ruby 1.9 after clone()
def initialize_copy(orig)
super
@states = orig.states.collect { |state| state.clone }
@events = {}
orig.events.each_pair { |name, event| @events[name] = event.clone }
@global_callbacks = @global_callbacks.dup
end
def add_state(state_name, klass, options)
set_initial_state(state_name, options)
# allow reloading, extending or redefining a state
@states.delete(state_name) if @states.include?(state_name)
@states << AASM::Core::State.new(state_name, klass, self, options)
end
def add_event(name, options, &block)
@events[name] = AASM::Core::Event.new(name, self, options, &block)
end
def add_global_callbacks(name, *callbacks, &block)
@global_callbacks[name] ||= []
callbacks.each do |callback|
@global_callbacks[name] << callback unless @global_callbacks[name].include? callback
end
@global_callbacks[name] << block if block
end
private
def set_initial_state(name, options)
@initial_state = name if options[:initial] || !initial_state
end
end # StateMachine
end # AASM