Skip to content

Commit 95fe5cf

Browse files
author
Lee Richmond
committed
Improve sideload recursion
* Better naming * Improved performance
1 parent 876d047 commit 95fe5cf

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed

lib/jsonapi_compliable/sideload.rb

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,18 @@ def initialize(name, type: nil, resource: nil, polymorphic: false, primary_key:
4444
end
4545

4646
# @api private
47-
def self.max_depth
48-
@max_depth || 2
47+
def self.max_recursion
48+
@max_recursion || 2
4949
end
5050

5151
# Set maximum levels of sideload recursion
5252
# /authors?comments.authors would be one level
5353
# /authors?comments.authors.comments.authors would be two levels
5454
# etc
5555
#
56-
# Default max depth is 2
57-
def self.max_depth=(val)
58-
@max_depth = val
56+
# Default max recursion is 2
57+
def self.max_recursion=(val)
58+
@max_recursion = val
5959
end
6060

6161
# @see #resource_class
@@ -382,17 +382,18 @@ def all_sideloads
382382
#
383383
# @return [Hash] The nested include hash
384384
# @api private
385-
def to_hash(depth_chain = [], parent = nil)
386-
depth = depth_chain.select { |arr| arr == [parent, self] }.length
387-
return {} if depth >= self.class.max_depth
385+
def to_hash(recursion_chain = [], parent = nil)
386+
recursing = ->(arr) { arr == [parent.object_id, self.object_id] }
387+
recursions = recursion_chain.select(&recursing).length
388+
return {} if recursions >= self.class.max_recursion
388389

389390
unless (parent && parent.name == :base) || name == :base
390-
depth_chain += [[parent, self]]
391+
recursion_chain += [[parent.object_id, self.object_id]]
391392
end
392393

393394
{ name => {} }.tap do |hash|
394395
all_sideloads.each_pair do |key, sl|
395-
sideload_hash = sl.to_hash(depth_chain, self)
396+
sideload_hash = sl.to_hash(recursion_chain, self)
396397
hash[name].merge!(sideload_hash)
397398
end
398399
end

spec/sideload_spec.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,10 @@ def foo
181181
end
182182

183183
around do |e|
184-
original = JsonapiCompliable::Sideload.max_depth
185-
JsonapiCompliable::Sideload.max_depth = 5
184+
original = JsonapiCompliable::Sideload.max_recursion
185+
JsonapiCompliable::Sideload.max_recursion = 5
186186
e.run
187-
JsonapiCompliable::Sideload.max_depth = original
187+
JsonapiCompliable::Sideload.max_recursion = original
188188
end
189189

190190
subject { ResourceA.new.sideloading.to_hash[:base] }

0 commit comments

Comments
 (0)