This repository was archived by the owner on Apr 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjsonapi_serializable_ext.rb
More file actions
67 lines (61 loc) · 2.26 KB
/
jsonapi_serializable_ext.rb
File metadata and controls
67 lines (61 loc) · 2.26 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
module Graphiti
module JsonapiSerializableExt
# This library looks up a serializer based on the record's class name
# This wouldn't work for us, since a model may be associated with
# multiple resources.
# Instead, this variable is assigned when the query is resolved
# To ensure we always render with the *resource* serializer
module RendererOverrides
def _build(object, exposures, klass)
resource = object.instance_variable_get(:@__graphiti_resource)
if resource.present?
klass = object.instance_variable_get(:@__graphiti_serializer)
klass.new(exposures.merge(object: object, resource: resource))
else
super(object, exposures, klass)
end
end
end
# See above comment
module RelationshipOverrides
def data
@_resources_block = proc do
resources = yield
if resources.nil? || Array(resources)[0].instance_variable_get(:@__graphiti_resource)
graphiti_data(resources)
else
jsonapi_data(resources)
end
end
end
def graphiti_data(resources)
if resources.nil?
nil
elsif resources.respond_to?(:to_ary)
Array(resources).map do |obj|
klass = obj.instance_variable_get(:@__graphiti_serializer)
resource = obj.instance_variable_get(:@__graphiti_resource)
klass.new(@_exposures.merge(object: obj, resource: resource))
end
else
klass = resources.instance_variable_get(:@__graphiti_serializer)
resource = resources.instance_variable_get(:@__graphiti_resource)
klass.new(@_exposures.merge(object: resources, resource: resource))
end
end
def jsonapi_data(resources)
if resources.nil?
nil
elsif resources.respond_to?(:to_ary)
Array(resources).map do |obj|
@_class[obj.class.name.to_sym].new(@_exposures.merge(object: obj))
end
else
@_class[resources.class.name.to_sym].new(@_exposures.merge(object: resources))
end
end
end
JSONAPI::Serializable::Relationship.send(:prepend, RelationshipOverrides)
JSONAPI::Serializable::Renderer.send(:prepend, RendererOverrides)
end
end