Class: JSONAPI::ResourceSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi/resource_serializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(primary_resource_klass, options = {}) ⇒ ResourceSerializer

initialize Options can include include:

Purpose: determines which objects will be side loaded with the source objects in a linked section
Example: ['comments','author','comments.tags','author.posts']

fields:

Purpose: determines which fields are serialized for a resource type. This encompasses both attributes and
         relationship ids in the links section for a resource. Fields are global for a resource type.
Example: { people: [:id, :email, :comments], posts: [:id, :title, :author], comments: [:id, :body, :post]}

key_formatter: KeyFormatter instance to override the default configuration serialization_options: additional options that will be passed to resource meta and links lambdas



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/jsonapi/resource_serializer.rb', line 22

def initialize(primary_resource_klass, options = {})
  @options                = options
  @primary_resource_klass = primary_resource_klass
  @fields                 = options.fetch(:fields, {})
  @include                = options.fetch(:include, [])
  @include_directives     = options.fetch(:include_directives,
                                          JSONAPI::IncludeDirectives.new(@primary_resource_klass, @include))
  @key_formatter          = options.fetch(:key_formatter, JSONAPI.configuration.key_formatter)
  @id_formatter           = ValueFormatter.value_formatter_for(:id)
  @link_builder           = generate_link_builder(primary_resource_klass, options)
  @always_include_to_one_linkage_data = options.fetch(:always_include_to_one_linkage_data,
                                                      JSONAPI.configuration.always_include_to_one_linkage_data)
  @always_include_to_many_linkage_data = options.fetch(:always_include_to_many_linkage_data,
                                                       JSONAPI.configuration.always_include_to_many_linkage_data)
  @serialization_options = options.fetch(:serialization_options, {})

  # Warning: This makes ResourceSerializer non-thread-safe. That's not a problem with the
  # request-specific way it's currently used, though.
  @value_formatter_type_cache = NaiveCache.new{|arg| ValueFormatter.value_formatter_for(arg) }

  @_config_keys = {}
  @_supplying_attribute_fields = {}
  @_supplying_relationship_fields = {}
end

Instance Attribute Details

#always_include_to_many_linkage_dataObject (readonly)

Returns the value of attribute always_include_to_many_linkage_data.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def always_include_to_many_linkage_data
  @always_include_to_many_linkage_data
end

#always_include_to_one_linkage_dataObject (readonly)

Returns the value of attribute always_include_to_one_linkage_data.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def always_include_to_one_linkage_data
  @always_include_to_one_linkage_data
end

#fieldsObject (readonly)

Returns the value of attribute fields.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def fields
  @fields
end

#include_directivesObject (readonly)

Returns the value of attribute include_directives.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def include_directives
  @include_directives
end

#key_formatterObject (readonly)

Returns the value of attribute key_formatter.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def key_formatter
  @key_formatter
end

Returns the value of attribute link_builder.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def link_builder
  @link_builder
end

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def options
  @options
end

#serialization_optionsObject (readonly)

Returns the value of attribute serialization_options.



6
7
8
# File 'lib/jsonapi/resource_serializer.rb', line 6

def serialization_options
  @serialization_options
end

Instance Method Details

#config_description(resource_klass) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/jsonapi/resource_serializer.rb', line 147

def config_description(resource_klass)
  {
    class_name: self.class.name,
    serialization_options: serialization_options.sort.map(&:as_json),
    supplying_attribute_fields: supplying_attribute_fields(resource_klass).sort,
    supplying_relationship_fields: supplying_relationship_fields(resource_klass).sort,
    link_builder_base_url: link_builder.base_url,
    key_formatter_class: key_formatter.uncached.class.name,
    always_include_to_one_linkage_data: always_include_to_one_linkage_data,
    always_include_to_many_linkage_data: always_include_to_many_linkage_data
  }
end

#config_key(resource_klass) ⇒ Object



139
140
141
142
143
144
145
# File 'lib/jsonapi/resource_serializer.rb', line 139

def config_key(resource_klass)
  @_config_keys.fetch resource_klass do
    desc = self.config_description(resource_klass).map(&:inspect).join(",")
    key = JSONAPI.configuration.resource_cache_digest_function.call(desc)
    @_config_keys[resource_klass] = "SRLZ-#{key}"
  end
end

#format_key(key) ⇒ Object



127
128
129
# File 'lib/jsonapi/resource_serializer.rb', line 127

def format_key(key)
  @key_formatter.format(key)
end

#format_value(value, format) ⇒ Object



135
136
137
# File 'lib/jsonapi/resource_serializer.rb', line 135

def format_value(value, format)
  @value_formatter_type_cache.get(format).format(value)
end

#object_hash(source, relationship_data) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/jsonapi/resource_serializer.rb', line 160

def object_hash(source, relationship_data)
  obj_hash = {}

  return obj_hash if source.nil?

  fetchable_fields = Set.new(source.fetchable_fields)

  if source.is_a?(JSONAPI::CachedResponseFragment)
    id_format = source.resource_klass._attribute_options(:id)[:format]

    id_format = 'id' if id_format == :default
    obj_hash['id'] = format_value(source.id, id_format)
    obj_hash['type'] = source.type

    obj_hash['links'] = source.links_json if source.links_json
    obj_hash['attributes'] = source.attributes_json if source.attributes_json

    relationships = cached_relationships_hash(source, fetchable_fields, relationship_data)
    obj_hash['relationships'] = relationships unless relationships.blank?

    obj_hash['meta'] = source.meta_json if source.meta_json
  else
    # TODO Should this maybe be using @id_formatter instead, for consistency?
    id_format = source.class._attribute_options(:id)[:format]
    # protect against ids that were declared as an attribute, but did not have a format set.
    id_format = 'id' if id_format == :default
    obj_hash['id'] = format_value(source.id, id_format)

    obj_hash['type'] = format_key(source.class._type.to_s)

    links = links_hash(source)
    obj_hash['links'] = links unless links.empty?

    attributes = attributes_hash(source, fetchable_fields)
    obj_hash['attributes'] = attributes unless attributes.empty?

    relationships = relationships_hash(source, fetchable_fields, relationship_data)
    obj_hash['relationships'] = relationships unless relationships.blank?

    meta = meta_hash(source)
    obj_hash['meta'] = meta unless meta.empty?
  end

  obj_hash
end


108
109
110
# File 'lib/jsonapi/resource_serializer.rb', line 108

def serialize_related_resource_set_to_hash_plural(resource_set, _source_resource)
  return serialize_resource_set_to_hash_plural(resource_set)
end

#serialize_resource_set_to_hash_plural(resource_set) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/jsonapi/resource_serializer.rb', line 85

def serialize_resource_set_to_hash_plural(resource_set)

  primary_objects = []
  included_objects = []

  resource_set.resource_klasses.each_value do |resource_klass|
    resource_klass.each_value do |resource|
      serialized_resource = object_hash(resource[:resource], resource[:relationships])

      if resource[:primary]
        primary_objects.push(serialized_resource)
      else
        included_objects.push(serialized_resource)
      end
    end
  end

  primary_hash = { 'data' => primary_objects }

  primary_hash['included'] = included_objects if included_objects.size > 0
  primary_hash
end

#serialize_resource_set_to_hash_single(resource_set) ⇒ Object

Converts a resource_set to a hash, conforming to the JSONAPI structure



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/jsonapi/resource_serializer.rb', line 61

def serialize_resource_set_to_hash_single(resource_set)

  primary_objects = []
  included_objects = []

  resource_set.resource_klasses.each_value do |resource_klass|
    resource_klass.each_value do |resource|
      serialized_resource = object_hash(resource[:resource], resource[:relationships])

      if resource[:primary]
        primary_objects.push(serialized_resource)
      else
        included_objects.push(serialized_resource)
      end
    end
  end

  fail "Too many primary objects for show" if (primary_objects.count > 1)
  primary_hash = { 'data' => primary_objects[0] }

  primary_hash['included'] = included_objects if included_objects.size > 0
  primary_hash
end

#serialize_to_hash(source) ⇒ Object

Converts a single resource, or an array of resources to a hash, conforming to the JSONAPI structure



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/jsonapi/resource_serializer.rb', line 48

def serialize_to_hash(source)
  include_related = include_directives[:include_related]
  resource_set = JSONAPI::ResourceSet.new(source, include_related, options)
  resource_set.populate!(self, options[:context], options)

  if source.is_a?(Array)
    serialize_resource_set_to_hash_plural(resource_set)
  else
    serialize_resource_set_to_hash_single(resource_set)
  end
end

#serialize_to_relationship_hash(source, requested_relationship, resource_ids) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/jsonapi/resource_serializer.rb', line 112

def serialize_to_relationship_hash(source, requested_relationship, resource_ids)
  if requested_relationship.is_a?(JSONAPI::Relationship::ToOne)
    data = to_one_linkage(resource_ids[0])
  else
    data = to_many_linkage(resource_ids)
  end

  rel_hash = { 'data': data }

  links = default_relationship_links(source, requested_relationship)
  rel_hash['links'] = links unless links.blank?

  rel_hash
end

#unformat_key(key) ⇒ Object



131
132
133
# File 'lib/jsonapi/resource_serializer.rb', line 131

def unformat_key(key)
  @key_formatter.unformat(key)
end