Skip to content

Commit

Permalink
Merge pull request rubysherpas#270 from unimatrixZxero/delete_all_fix
Browse files Browse the repository at this point in the history
Ensure delete_all and destroy_all are paranoid
  • Loading branch information
Kurtis Rainbolt-Greene committed Feb 9, 2016
2 parents 31b5db1 + ce7670c commit bd33837
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/paranoia.rb
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,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
Expand Down
58 changes: 58 additions & 0 deletions test/paranoia_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,64 @@ 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

def test_destroy_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.destroy_all

assert_equal 0, model.count
assert_equal 3, model.unscoped.count
end

def test_destroy_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.destroy_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
Expand Down

0 comments on commit bd33837

Please sign in to comment.