-
Notifications
You must be signed in to change notification settings - Fork 533
/
Copy pathinclude_directives.rb
47 lines (39 loc) · 1.22 KB
/
include_directives.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module JSONAPI
class IncludeDirectives
# Construct an IncludeDirectives Hash from an array of dot separated include strings.
# For example ['posts.comments.tags']
# will transform into =>
# {
# posts: {
# comments: {
# tags: {}
# }
# }
# }
def initialize(resource_klass, includes_array)
@resource_klass = resource_klass
@include_directives_hash = {}
includes_array.each do |include|
parse_include(include)
end
end
def include_directives
@include_directives_hash
end
private
def parse_include(include)
path = JSONAPI::Path.new(resource_klass: @resource_klass,
path_string: include,
ensure_default_field: false,
parse_fields: false)
current = @include_directives_hash
path.segments.each do |segment|
relationship_name = segment.relationship.name.to_sym
current[relationship_name] ||= {}
current = current[relationship_name]
end
rescue JSONAPI::Exceptions::InvalidRelationship => _e
raise JSONAPI::Exceptions::InvalidInclude.new(@resource_klass, include)
end
end
end