File tree Expand file tree Collapse file tree 3 files changed +52
-1
lines changed Expand file tree Collapse file tree 3 files changed +52
-1
lines changed Original file line number Diff line number Diff line change @@ -1577,6 +1577,7 @@ To have Mongoid raise an error when a scope would overwrite an existing class
1577
1577
method, set the ``scope_overwrite_exception`` :ref:`configuration option
1578
1578
<configuration-options>` to ``true``.
1579
1579
1580
+
1580
1581
Default Scopes
1581
1582
--------------
1582
1583
@@ -1705,6 +1706,35 @@ that would affect its visibility within the scoped association.
1705
1706
label.reload.bands # []
1706
1707
1707
1708
1709
+ Runtime Default Scope Override
1710
+ ------------------------------
1711
+
1712
+ You can use the ``with_scope`` method to change the default scope in a block
1713
+ at runtime:
1714
+
1715
+ .. code-block:: ruby
1716
+
1717
+ class Band
1718
+ include Mongoid::Document
1719
+ field :country, type: String
1720
+ field :genres, type: Array
1721
+
1722
+ scope :english, ->{ where(country: "England") }
1723
+ end
1724
+
1725
+ criteria = Band.with_scope(Band.english) do
1726
+ Band.all
1727
+ end
1728
+
1729
+ criteria
1730
+ # =>
1731
+ # #<Mongoid::Criteria
1732
+ # selector: {"country"=>"England"}
1733
+ # options: {}
1734
+ # class: Band
1735
+ # embedded: false>
1736
+
1737
+
1708
1738
Class Methods
1709
1739
-------------
1710
1740
Original file line number Diff line number Diff line change @@ -203,11 +203,12 @@ def with_default_scope
203
203
#
204
204
# @return [ Criteria ] The yielded criteria.
205
205
def with_scope ( criteria )
206
+ previous = Threaded . current_scope ( self )
206
207
Threaded . set_current_scope ( criteria , self )
207
208
begin
208
209
yield criteria
209
210
ensure
210
- Threaded . set_current_scope ( nil , self )
211
+ Threaded . set_current_scope ( previous , self )
211
212
end
212
213
end
213
214
Original file line number Diff line number Diff line change @@ -1126,6 +1126,26 @@ class << Band
1126
1126
expect ( Mongoid ::Threaded . current_scope ( Band ) ) . to be_nil
1127
1127
end
1128
1128
end
1129
+
1130
+ context 'when nesting with_scope calls' do
1131
+ let ( :c1 ) { Band . where ( active : true ) }
1132
+ let ( :c2 ) { Band . where ( active : false ) }
1133
+
1134
+ it 'restores previous scope' do
1135
+ Band . with_scope ( c1 ) do |crit |
1136
+ Band . with_scope ( c2 ) do |crit2 |
1137
+ Mongoid ::Threaded . current_scope ( Band ) . selector . should == {
1138
+ 'active' => true ,
1139
+ '$and' => [ 'active' => false ] ,
1140
+ }
1141
+ end
1142
+
1143
+ Mongoid ::Threaded . current_scope ( Band ) . selector . should == {
1144
+ 'active' => true ,
1145
+ }
1146
+ end
1147
+ end
1148
+ end
1129
1149
end
1130
1150
1131
1151
describe ".without_default_scope" do
You can’t perform that action at this time.
0 commit comments