From 1fc916b976dd504766ff176d5259163def65e150 Mon Sep 17 00:00:00 2001 From: Sam Figueroa Date: Fri, 16 Oct 2015 08:06:12 +0200 Subject: [PATCH] Add delete_all to paranoid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - don’t let people destroy paranoid models with delete_all --- lib/paranoia.rb | 4 ++++ test/paranoia_test.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/paranoia.rb b/lib/paranoia.rb index 75e9c5eb..5b478295 100644 --- a/lib/paranoia.rb +++ b/lib/paranoia.rb @@ -249,6 +249,10 @@ def self.I_AM_THE_DESTROYER! def self.paranoid? ; false ; end def paranoid? ; self.class.paranoid? ; end + def self.delete_all(conditions=nil) + super and return unless paranoid? + where(conditions).update_all(self.new.send :paranoia_destroy_attributes) + end private def paranoia_column diff --git a/test/paranoia_test.rb b/test/paranoia_test.rb index f6fe129a..321c97ea 100644 --- a/test/paranoia_test.rb +++ b/test/paranoia_test.rb @@ -879,6 +879,36 @@ def test_uniqueness_for_unparanoid_associated related.valid? end + def test_delete_all + model = ParanoidModel + count = 3 + models = count.times.map { model.new } + assert_equal 0, model.count + models.each(&:save!) + + assert_equal count, model.count + model.delete_all + + assert_equal 0, model.count + assert_equal count, model.with_deleted.count + + assert model.with_deleted.all?(&:deleted?) + end + + def test_delete_all_for_non_paranoid_model + model = PlainModel + count = 3 + models = count.times.map { model.new } + assert_equal 0, model.count + models.each(&:save!) + + assert_equal count, model.count + model.delete_all + + assert_equal 0, model.count + assert_equal 0, model.unscoped.count + end + # TODO: find a fix for Rails 4.1 if ActiveRecord::VERSION::STRING !~ /\A4\.1/ def test_counter_cache_column_update_on_really_destroy