diff --git a/lib/discard/model.rb b/lib/discard/model.rb index 5ba0740..711d485 100644 --- a/lib/discard/model.rb +++ b/lib/discard/model.rb @@ -117,9 +117,15 @@ def undiscarded? # @return [Boolean] true if successful, otherwise false def discard return false if discarded? - run_callbacks(:discard) do - update_attribute(self.class.discard_column, Time.current) + + _in_discard_transaction do + run_callbacks(:discard) do + update_attribute(self.class.discard_column, Time.current) + end end + + rescue Exception => e + handle_transaction_rollback(e) end # Discard the record in the database @@ -131,7 +137,9 @@ def discard # @return [Boolean] true if successful # @raise {Discard::RecordNotDiscarded} def discard! - discard || _raise_record_not_discarded + with_transaction_returning_status do + discard || _raise_record_not_discarded + end end # Undiscard the record in the database @@ -139,8 +147,11 @@ def discard! # @return [Boolean] true if successful, otherwise false def undiscard return unless discarded? - run_callbacks(:undiscard) do - update_attribute(self.class.discard_column, nil) + + _in_discard_transaction do + run_callbacks(:undiscard) do + update_attribute(self.class.discard_column, nil) + end end end @@ -158,6 +169,18 @@ def undiscard! private + def _in_discard_transaction + previous_discard_value = public_send(self.class.discard_column) + + with_transaction_returning_status do + yield + end + rescue Exception => exception + assign_attributes(self.class.discard_column => previous_discard_value) + + raise exception + end + def _raise_record_not_discarded raise ::Discard::RecordNotDiscarded.new("Failed to discard the record", self) end