Skip to content

Commit

Permalink
Fix single rel caching issue (#1713)
Browse files Browse the repository at this point in the history
  • Loading branch information
huseynov206 authored Dec 28, 2023
1 parent defccda commit dba8fa2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/active_graph/node/has_n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,17 @@ def init_cache

def add_to_cache(object, rel = nil)
(@cached_rels ||= []) << rel if rel
(@cached_result ||= []).tap { |results| results << object if object && !results.include?(object) }
(@cached_result ||= []).tap { |results| results << object if !results.include?(object) } if object
end

def rels
@cached_rels || super.tap { |rels| rels.each { |rel| add_to_cache(nil, rel) } }
end

def rel
rels.first
end

def cache_query_proxy_result
(result_cache_proc_cache || @query_proxy).to_a.tap { |result| cache_result(result) }
end
Expand Down
24 changes: 22 additions & 2 deletions spec/e2e/association_proxy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
has_one :out, :favorite_lesson, type: nil, model_class: :Lesson
has_many :out, :homework, type: :HOMEWORK, model_class: %w[Lesson Exam]
has_many :out, :friends, type: :friend, model_class: :Student
has_one :out, :school, rel_class: :SchoolRel
end

stub_relationship_class('LessonEnrollment') do
from_class :Student
to_class :Lesson
type :has_studet
type :has_student

property :grade
end
Expand All @@ -34,6 +35,17 @@
has_many :in, :lessons, model_class: :Lesson, origin: :exams_given
has_many :out, :students, type: :has_student, model_class: :Student
end

stub_relationship_class('SchoolRel') do
from_class :Student
to_class :School
type :school
end

stub_node_class('School') do
property :name
has_many :out, :students, type: :school, model_class: :School
end
end

let(:billy) { Student.create(name: 'Billy') }
Expand All @@ -44,6 +56,7 @@
let(:science_exam2) { Exam.create(name: 'Science Exam 2') }
let(:leszek) { Student.create(name: 'Leszek', friends: [zinto]) }
let(:zinto) { Student.create(name: 'Zinto') }
let(:code_academy) { School.create(name: 'Code Academy') }

before do
[math, science].each { |lesson| billy.lessons << lesson }
Expand All @@ -52,6 +65,7 @@
science.exams_given << science_exam
science.exams_given << science_exam2
billy.favorite_lesson = math
billy.school = code_academy
end

context 'self referencing relationships' do
Expand Down Expand Up @@ -313,11 +327,17 @@
end

describe '#rels' do
it 'caches results for consecutive calls' do
it 'caches multi rels for consecutive calls' do
expect_queries(1) do
2.times { billy.lessons.rels }
end
end

it 'caches single rel for consecutive calls' do
expect_queries(1) do
2.times { billy.school(chainable: true).rel }
end
end
end

describe '#inspect' do
Expand Down

0 comments on commit dba8fa2

Please sign in to comment.