Skip to content

Commit

Permalink
pass event args to after_failure callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
kfalconer committed Oct 28, 2017
1 parent 8bdfb69 commit f3d5fa8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/state_machines/event.rb
Expand Up @@ -154,18 +154,20 @@ def fire(object, *args)
if transition = transition_for(object)
transition.perform(*args)
else
on_failure(object)
on_failure(object, *args)
false
end
end

# Marks the object as invalid and runs any failure callbacks associated with
# this event. This should get called anytime this event fails to transition.
def on_failure(object)
def on_failure(object, *args)
state = machine.states.match!(object)
machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]])

Transition.new(object, machine, name, state.name, state.name).run_callbacks(:before => false)
transition = Transition.new(object, machine, name, state.name, state.name)
transition.args = args if args.any?
transition.run_callbacks(:before => false)
end

# Resets back to the initial state of the event, with no branches / known
Expand Down
13 changes: 13 additions & 0 deletions test/unit/event/event_on_failure_test.rb
Expand Up @@ -36,6 +36,19 @@ def test_should_run_failure_callbacks
assert_equal :ignite, transition.event
assert_equal :parked, transition.from_name
assert_equal :parked, transition.to_name
assert_equal [], transition.args
end

def test_should_pass_args_to_failure_callbacks
callback_args = nil
@machine.after_failure { |*args| callback_args = args }

@event.fire(@object, foo: 'bar')

object, transition = callback_args
assert_equal @object, object
refute_nil transition
assert_equal [{foo: 'bar'}], transition.args
end

def teardown
Expand Down

0 comments on commit f3d5fa8

Please sign in to comment.