Do not call callbacks when they are disabled #162

Closed
wants to merge 1 commit into
from
View
5 lib/state_machine/integrations/active_model/observer.rb
@@ -21,7 +21,10 @@ module ActiveModel
module Observer
def update_with_transition(args)
observed_method, object, transition = args
- send(observed_method, object, transition) if respond_to?(observed_method)
+ return unless respond_to?(observed_method)
+ return if disabled_for?(object)
+
+ send(observed_method, object, transition)
end
end
end
View
31 test/unit/integrations/active_model_test.rb
@@ -764,6 +764,37 @@ def test_should_call_all_transition_callback_permutations
@transition.perform
assert_equal callbacks, instance.notifications
end
+
+ def test_should_call_no_transition_callbacks_when_observers_disabled
+ callbacks = [
+ :before_ignite_from_parked_to_idling,
+ :before_ignite_from_parked,
+ :before_ignite_to_idling,
+ :before_ignite,
+ :before_transition_state_from_parked_to_idling,
+ :before_transition_state_from_parked,
+ :before_transition_state_to_idling,
+ :before_transition_state,
+ :before_transition
+ ]
+
+ notified = false
+ observer = new_observer(@model) do
+ callbacks.each do |callback|
+ define_method(callback) do |*args|
+ notifications << callback
+ end
+ end
+ end
+
+ instance = observer.instance
+
+ @model.observers.disable observer do
+ @transition.perform
+ end
+
+ assert_equal [], instance.notifications
+ end
def test_should_pass_record_and_transition_to_before_callbacks
observer = new_observer(@model) do
View
33 test/unit/integrations/active_record_test.rb
@@ -1585,7 +1585,38 @@ def test_should_call_all_transition_callback_permutations
@transition.perform
assert_equal callbacks, instance.notifications
end
-
+
+ def test_should_call_no_transition_callbacks_when_observers_disabled
+ callbacks = [
+ :before_ignite_from_parked_to_idling,
+ :before_ignite_from_parked,
+ :before_ignite_to_idling,
+ :before_ignite,
+ :before_transition_state_from_parked_to_idling,
+ :before_transition_state_from_parked,
+ :before_transition_state_to_idling,
+ :before_transition_state,
+ :before_transition
+ ]
+
+ notified = false
+ observer = new_observer(@model) do
+ callbacks.each do |callback|
+ define_method(callback) do |*args|
+ notifications << callback
+ end
+ end
+ end
+
+ instance = observer.instance
+
+ @model.observers.disable observer do
+ @transition.perform
+ end
+
+ assert_equal [], instance.notifications
+ end
+
def test_should_pass_record_and_transition_to_before_callbacks
observer = new_observer(@model) do
def before_transition(*args)