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


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

def initialize(primary_resource_klass, options = {})
  @primary_resource_klass = primary_resource_klass
  @fields                 = options.fetch(:fields, {})
  @include                = options.fetch(:include, [])
  @include_directives     = options[:include_directives]
  @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


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

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


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def always_include_to_one_linkage_data
  @always_include_to_one_linkage_data
end

#fieldsObject (readonly)

Returns the value of attribute fields


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def fields
  @fields
end

#include_directivesObject (readonly)

Returns the value of attribute include_directives


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def include_directives
  @include_directives
end

#key_formatterObject (readonly)

Returns the value of attribute key_formatter


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def key_formatter
  @key_formatter
end

Returns the value of attribute link_builder


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def link_builder
  @link_builder
end

#serialization_optionsObject (readonly)

Returns the value of attribute serialization_options


4
5
6
# File 'lib/jsonapi/resource_serializer.rb', line 4

def serialization_options
  @serialization_options
end

Instance Method Details

#config_description(resource_klass) ⇒ Object


131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/jsonapi/resource_serializer.rb', line 131

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


123
124
125
126
127
128
129
# File 'lib/jsonapi/resource_serializer.rb', line 123

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


111
112
113
# File 'lib/jsonapi/resource_serializer.rb', line 111

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

#format_value(value, format) ⇒ Object


119
120
121
# File 'lib/jsonapi/resource_serializer.rb', line 119

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

#object_hash(source, relationship_data) ⇒ Object


144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
# File 'lib/jsonapi/resource_serializer.rb', line 144

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

92
93
94
# File 'lib/jsonapi/resource_serializer.rb', line 92

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


69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/jsonapi/resource_serializer.rb', line 69

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


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/jsonapi/resource_serializer.rb', line 45

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_relationship_hash(source, requested_relationship, resource_ids) ⇒ Object


96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/jsonapi/resource_serializer.rb', line 96

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


115
116
117
# File 'lib/jsonapi/resource_serializer.rb', line 115

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