Skip to content

Commit

Permalink
cleanup and fix race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
simkim committed Nov 3, 2022
1 parent e1519eb commit d41a696
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 31 deletions.
38 changes: 10 additions & 28 deletions lib/couchbase-orm/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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
6 changes: 3 additions & 3 deletions spec/relation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -311,26 +311,26 @@ 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)
_m2 = RelationModel.create!(age: 20, active: false)
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

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
Expand Down

0 comments on commit d41a696

Please sign in to comment.