Skip to content

Commit

Permalink
Allow the transitions / known states for an event to be reset
Browse files Browse the repository at this point in the history
  • Loading branch information
obrie committed Nov 13, 2011
1 parent 8f71eb1 commit e9c640f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
@@ -1,5 +1,6 @@
# master

* Allow the transitions / known states for an event to be reset
* Add fire_#{name}_event instance method for firing an arbitrary event on a state machine
* Improve InvalidTransition exception messages to include the failure reason(s) in ORM integrations
* Don't allow around_transitions to attempt to be called in multiple execution contexts when run in jruby
Expand Down
12 changes: 10 additions & 2 deletions lib/state_machine/event.rb
Expand Up @@ -55,8 +55,7 @@ def initialize(machine, name, options = {}) #:nodoc:
@name = name
@qualified_name = machine.namespace ? :"#{name}_#{machine.namespace}" : name
@human_name = options[:human_name] || @name.to_s.tr('_', ' ')
@branches = []
@known_states = []
reset

# Output a warning if another event has a conflicting qualified name
if conflict = machine.owner_class.state_machines.detect {|name, other_machine| other_machine != @machine && other_machine.events[qualified_name, :qualified_name]}
Expand Down Expand Up @@ -186,6 +185,15 @@ def on_failure(object)
Transition.new(object, machine, name, state.name, state.name).run_callbacks(:before => false)
end

# Resets back to the initial state of the event, with no branches / known
# states associated. This allows you to redefine an event in situations
# where you either are re-using an existing state machine implementation
# or are subclassing machines.
def reset
@branches = []
@known_states = []
end

# Draws a representation of this event on the given graph. This will
# create 1 or more edges on the graph for each branch (i.e. transition)
# configured.
Expand Down
10 changes: 10 additions & 0 deletions test/unit/event_test.rb
Expand Up @@ -474,6 +474,11 @@ def test_should_include_new_transition_states_after_calling_known_states
assert_equal [:parked, :idling, :first_gear, :stalled], @event.known_states
end

def test_should_clear_known_states_on_reset
@event.reset
assert_equal [], @event.known_states
end

def test_should_use_pretty_inspect
assert_match "#<StateMachine::Event name=:ignite transitions=[:parked => :idling, :first_gear => :idling]>", @event.inspect
end
Expand Down Expand Up @@ -690,6 +695,11 @@ def test_should_not_invalidate_the_state
assert_equal [], @object.errors
end

def test_should_not_be_able_to_fire_on_reset
@event.reset
assert !@event.can_fire?(@object)
end

def teardown
StateMachine::Integrations.send(:remove_const, 'Custom')
end
Expand Down

0 comments on commit e9c640f

Please sign in to comment.