Module: JsonapiSerializer::Base
- Extended by:
- ActiveSupport::Concern
- Includes:
- Common, DSL::Common, Utils
- Defined in:
- lib/jsonapi_serializer/base.rb
Instance Method Summary
collapse
Methods included from Common
#serializable_hash, #serialized_json, #type
Methods included from Utils
#apply_splat, #key_intersect, #normalize_fields, #normalize_includes
Instance Method Details
#attributes_hash(record) ⇒ Object
34
35
36
37
38
|
# File 'lib/jsonapi_serializer/base.rb', line 34
def attributes_hash(record)
@attributes.each_with_object({}) do |(key, val), hash|
hash[key] = val.call(record)
end
end
|
#id_hash(record) ⇒ Object
30
31
32
|
# File 'lib/jsonapi_serializer/base.rb', line 30
def id_hash(record)
{id: @id.call(record), type: @type}
end
|
#initialize(opts = {}) ⇒ Object
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/jsonapi_serializer/base.rb', line 14
def initialize(opts = {})
super(opts)
@id = self.class.meta_id
unless opts[:id_only]
fields = normalize_fields(opts.fetch(:fields, {}))
if opts[:poly_fields].present?
fields[@type] = fields.fetch(@type, []) + opts[:poly_fields]
end
includes = normalize_includes(opts.fetch(:include, {}))
prepare_attributes(fields)
prepare_relationships(fields, includes)
end
end
|
#record_hash(record, context = {}) ⇒ Object
57
58
59
60
61
62
63
64
65
|
# File 'lib/jsonapi_serializer/base.rb', line 57
def record_hash(record, context = {})
hash = id_hash(record)
if context[:tracker]
(context[:tracker][hash[:type]] ||= Set.new).add?(hash[:id])
end
hash[:attributes] = attributes_hash(record) if @attributes.present?
hash[:relationships] = relationships_hash(record, context) if @relationships.present?
hash
end
|
#relationships_hash(record, context = {}) ⇒ Object
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
# File 'lib/jsonapi_serializer/base.rb', line 40
def relationships_hash(record, context = {})
@relationships.each_with_object({}) do |(key, from, serializer, included), hash|
if relation = from.call(record)
if relation.respond_to?(:map)
relation_ids = relation.map do |item|
process_relation(item, serializer, context, included)
end
hash[key] = {data: relation_ids}
else
hash[key] = {data: process_relation(relation, serializer, context, included)}
end
else
hash[key] = {data: nil}
end
end
end
|