diff --git a/lib/couchbase-orm/relation.rb b/lib/couchbase-orm/relation.rb index 8ea615d8..140040ff 100644 --- a/lib/couchbase-orm/relation.rb +++ b/lib/couchbase-orm/relation.rb @@ -128,6 +128,14 @@ def all CouchbaseOrm_Relation.new(**initializer_arguments) end + def scoping + scopes = (Thread.current[@model.name] ||= []) + scopes.push(self) + result = yield + scopes.pop + result + end + private def build_limit @@ -171,14 +179,6 @@ def build_update(**cond) end.join(", ") end - def scoping - scopes = (Thread.current[@model.name] ||= []) - scopes.push(self) - result = yield - scopes.pop - result - end - def method_missing(method, *args, &block) if @model.respond_to?(method) scoping { @@ -195,27 +195,9 @@ def relation Thread.current[self.name]&.last || CouchbaseOrm_Relation.new(model: self) end - def where(**conds) - relation.where(**conds) - end - - def not(**conds) - relation.not(**conds) - end - - def order(*ordersl, **ordersh) - relation.order(*ordersl, **ordersh) - end - - def limit(limit) - relation.limit(limit) - end - - def all - relation.all - end - delegate :ids, :delete_all, :count, :empty?, :filter, :reduce, :find_by, to: :all + + delegate :where, :not, :order, :limit, :all, to: :relation end end end diff --git a/spec/relation_spec.rb b/spec/relation_spec.rb index 9d68e172..c6e0a9b1 100644 --- a/spec/relation_spec.rb +++ b/spec/relation_spec.rb @@ -311,6 +311,7 @@ def self.test(&block) expect(m3.reload.age).to eq(50) expect(m4.reload.age).to eq(40) end + describe "scopes" do it "should chain scopes" do _m1 = RelationModel.create!(age: 10, active: true) @@ -318,7 +319,6 @@ def self.test(&block) m3 = RelationModel.create!(age: 30, active: true) m4 = RelationModel.create!(age: 40, active: true) - expect(RelationModel.all.adult.all.active.all).to match_array([m3, m4]) expect(RelationModel.where(active: true).adult).to match_array([m3, m4]) end @@ -326,11 +326,11 @@ def self.test(&block) it "should be thread safe" do m1 = RelationModel.create!(age: 10, active: true) m2 = RelationModel.create!(age: 20, active: false) - RelationModel.active.test do + RelationModel.active.scoping do expect(RelationModel.all).to match_array([m1]) Thread.start do expect(RelationModel.all).to match_array([m1, m2]) - end + end.join end end end