Skip to content

Commit 3edb851

Browse files
committed
add with_deleted scope
1 parent 52b652f commit 3edb851

3 files changed

Lines changed: 52 additions & 0 deletions

File tree

lib/mongoid/paranoia.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ def configure
4646

4747
default_scope -> { where(deleted_at: nil) }
4848
scope :deleted, -> { ne(deleted_at: nil) }
49+
scope :with_deleted, lambda {
50+
msg = 'This scope requires Mongoid >= 9 and allow_scopes_to_unset_default_scope to be set to true'
51+
raise msg unless Mongoid.try(:allow_scopes_to_unset_default_scope)
52+
53+
criteria.remove_scoping(unscoped.where(deleted_at: nil))
54+
}
4955
define_model_callbacks :restore
5056
define_model_callbacks :remove
5157
end

spec/mongoid/paranoia_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,29 @@ class ParanoidConfiguredReset
9898
end
9999
end
100100

101+
describe ".with_deleted" do
102+
103+
let(:posts) do
104+
2.times { |i| ParanoidPost.create(title: "testing #{i}") }
105+
end
106+
107+
before do
108+
Mongoid.configure do |config|
109+
config.try(:allow_scopes_to_unset_default_scope=, true)
110+
end
111+
112+
posts.first.destroy
113+
end
114+
115+
let(:with_deleted) do
116+
ParanoidPost.with_deleted
117+
end
118+
119+
it "returns the deleted documents" do
120+
expect(with_deleted).to eq(posts)
121+
end
122+
end if respond_to?(:allow_scopes_to_unset_default_scope=)
123+
101124
describe "#destroy!" do
102125

103126
context "when the document is a root" do

spec/mongoid/scoping_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,28 @@
5151
expect(criteria.selector).to eq({ "fresh" => true })
5252
end
5353
end
54+
55+
context "when chaining with_deleted" do
56+
57+
let(:criteria) do
58+
Fish.fresh.with_deleted
59+
end
60+
61+
if respond_to?(:allow_scopes_to_unset_default_scope=)
62+
before do
63+
Mongoid.configure do |config|
64+
config.try(:allow_scopes_to_unset_default_scope=, true)
65+
end
66+
67+
it "removes only deleted_at from the selector" do
68+
expect(criteria.selector).to eq({ "fresh" => true })
69+
end
70+
end
71+
else
72+
it "raises an error if the feature is not supported" do
73+
expect { criteria.selector }.to raise_error(/requires Mongoid >= 9/)
74+
end
75+
end
76+
end
5477
end
5578
end

0 commit comments

Comments
 (0)