Class: SimpleJsonApi::ResourceSerializer
Overview
The Serializer will serialize a model
Instance Attribute Summary
Attributes inherited from Serializer
#_builder, #_each_serializer, #_object
Attributes included from DSL
#_attributes
Instance Method Summary
collapse
Methods inherited from Serializer
for, for_polymorphic, for_regular, #initialize, register_serializer
Methods included from DSL
#attribute, #belongs_to, #default_fields, #has_many, #has_one, #inherited, #serializes
Instance Method Details
#_association_values ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
|
# File 'lib/simple_json_api/resource_serializer.rb', line 55
def _association_values
_associations.each do |association|
name = association[:name]
obj = send(name)
_builder.add_linked_elem(
name,
obj,
association,
@_base
)
end
end
|
#_associations ⇒ Object
51
52
53
|
# File 'lib/simple_json_api/resource_serializer.rb', line 51
def _associations
self.class._associations
end
|
#_fields ⇒ Object
11
12
13
14
15
16
17
|
# File 'lib/simple_json_api/resource_serializer.rb', line 11
def _fields
@_fields ||= begin
defaults = self.class.default_fields.split(',')
builders = _builder.fields_for(_root_name).presence
(builders || defaults).map(&:to_sym)
end
end
|
#_root_name ⇒ Object
7
8
9
|
# File 'lib/simple_json_api/resource_serializer.rb', line 7
def _root_name
self.class._root_name
end
|
#attribute_values(hash) ⇒ Object
27
28
29
30
31
32
|
# File 'lib/simple_json_api/resource_serializer.rb', line 27
def attribute_values(hash)
_fields.each do |attribute, _attr_opts|
hash[attribute] = send(attribute).to_s
end
hash[:href] = href if self.class.method_defined? :href
end
|
#link(association) ⇒ Object
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/simple_json_api/resource_serializer.rb', line 40
def link(association)
resource = send(association.name)
if association.type == :has_many
resource.to_a.map do |obj|
association[:polymorphic] ? obj.typed_json_id : obj.json_id
end
else
resource.json_id
end
end
|
#link_values(root) ⇒ Object
34
35
36
37
38
|
# File 'lib/simple_json_api/resource_serializer.rb', line 34
def link_values(root)
self.class._associations.each do |association|
root[association.key] = link(association)
end
end
|
#serialize ⇒ Object
19
20
21
22
23
24
25
|
# File 'lib/simple_json_api/resource_serializer.rb', line 19
def serialize
hash = {}
attribute_values(hash)
link_values(hash[:links] = {})
_association_values
hash
end
|