Module: JSONAPI::Serializer
- Defined in:
- lib/jsonapi-serializers.rb,
lib/jsonapi-serializers/version.rb,
lib/jsonapi-serializers/serializer.rb
Defined Under Namespace
Modules: ClassMethods, InstanceMethods Classes: AmbiguousCollectionError, Error, InvalidIncludeError
Constant Summary collapse
- VERSION =
'0.3.1'
Class Method Summary collapse
-
.find_recursive_relationships(root_object, root_inclusion_tree, results) ⇒ Object
Recursively find object relationships and returns a tree of related objects.
- .find_serializer(object) ⇒ Object
- .find_serializer_class(object) ⇒ Object
- .find_serializer_class_name(object) ⇒ Object
- .included(target) ⇒ Object
- .merge_relationship_path(path, data) ⇒ Object
-
.parse_relationship_paths(paths) ⇒ Object
Takes a list of relationship paths and returns a hash as deep as the given paths.
- .serialize(objects, options = {}) ⇒ Object
- .serialize_primary(object, options = {}) ⇒ Object
- .serialize_primary_multi(objects, options = {}) ⇒ Object
Class Method Details
.find_recursive_relationships(root_object, root_inclusion_tree, results) ⇒ Object
Recursively find object relationships and returns a tree of related objects. Example return:
['comments', '1'] => {object: <Comment>, include_linkages: ['author'],
['users', '1'] => <User>, include_linkages: [],
['users', '2'] => <User>, include_linkages: [],
}
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'lib/jsonapi-serializers/serializer.rb', line 355 def self.find_recursive_relationships(root_object, root_inclusion_tree, results) root_inclusion_tree.each do |attribute_name, child_inclusion_tree| # Skip the sentinal value, but we need to preserve it for siblings. next if attribute_name == :_include serializer = JSONAPI::Serializer.find_serializer(root_object) unformatted_attr_name = serializer.unformat_name(attribute_name).to_sym # We know the name of this relationship, but we don't know where it is stored internally. # Check if it is a has_one or has_many relationship. object = nil is_collection = false is_valid_attr = false if serializer.has_one_relationships.has_key?(unformatted_attr_name) is_valid_attr = true attr_data = serializer.has_one_relationships[unformatted_attr_name] object = serializer.has_one_relationship(unformatted_attr_name, attr_data) elsif serializer.has_many_relationships.has_key?(unformatted_attr_name) is_valid_attr = true is_collection = true attr_data = serializer.has_many_relationships[unformatted_attr_name] object = serializer.has_many_relationship(unformatted_attr_name, attr_data) end if !is_valid_attr raise JSONAPI::Serializer::InvalidIncludeError.new( "'#{attribute_name}' is not a valid include.") end if attribute_name.include?('_') expected_name = serializer.format_name(attribute_name) raise JSONAPI::Serializer::InvalidIncludeError.new( "'#{attribute_name}' is not a valid include. Did you mean '#{expected_name}' ?" ) end # We're finding relationships for compound documents, so skip anything that doesn't exist. next if object.nil? # We only include parent values if the sential value _include is set. This satifies the # spec note: A request for comments.author should not automatically also include comments # in the response. This can happen if the client already has the comments locally, and now # wants to fetch the associated authors without fetching the comments again. # http://jsonapi.org/format/#fetching-includes objects = is_collection ? object : [object] if child_inclusion_tree[:_include] == true # Include the current level objects if the _include attribute exists. # If it is not set, that indicates that this is an inner path and not a leaf and will # be followed by the recursion below. objects.each do |obj| obj_serializer = JSONAPI::Serializer.find_serializer(obj) # Use keys of ['posts', '1'] for the results to enforce uniqueness. # Spec: A compound document MUST NOT include more than one resource object for each # type and id pair. # http://jsonapi.org/format/#document-structure-compound-documents key = [obj_serializer.type, obj_serializer.id] # This is special: we know at this level if a child of this parent will also been # included in the compound document, so we can compute exactly what linkages should # be included by the object at this level. This satisfies this part of the spec: # # Spec: Resource linkage in a compound document allows a client to link together # all of the included resource objects without having to GET any relationship URLs. # http://jsonapi.org/format/#document-structure-resource-relationships current_child_includes = [] inclusion_names = child_inclusion_tree.keys.reject { |k| k == :_include } inclusion_names.each do |inclusion_name| if child_inclusion_tree[inclusion_name][:_include] current_child_includes << inclusion_name end end # Special merge: we might see this object multiple times in the course of recursion, # so merge the include_linkages each time we see it to load all the relevant linkages. current_child_includes += results[key] && results[key][:include_linkages] || [] current_child_includes.uniq! results[key] = {object: obj, include_linkages: current_child_includes} end end # Recurse deeper! if !child_inclusion_tree.empty? # For each object we just loaded, find all deeper recursive relationships. objects.each do |obj| find_recursive_relationships(obj, child_inclusion_tree, results) end end end nil end |
.find_serializer(object) ⇒ Object
222 223 224 |
# File 'lib/jsonapi-serializers/serializer.rb', line 222 def self.find_serializer(object) find_serializer_class(object).new(object) end |
.find_serializer_class(object) ⇒ Object
217 218 219 220 |
# File 'lib/jsonapi-serializers/serializer.rb', line 217 def self.find_serializer_class(object) class_name = find_serializer_class_name(object) class_name.constantize end |
.find_serializer_class_name(object) ⇒ Object
213 214 215 |
# File 'lib/jsonapi-serializers/serializer.rb', line 213 def self.find_serializer_class_name(object) "#{object.class.name}Serializer" end |
.included(target) ⇒ Object
6 7 8 9 10 11 12 |
# File 'lib/jsonapi-serializers/serializer.rb', line 6 def self.included(target) target.send(:include, InstanceMethods) target.extend ClassMethods target.class_eval do include JSONAPI::Attributes end end |
.merge_relationship_path(path, data) ⇒ Object
465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/jsonapi-serializers/serializer.rb', line 465 def self.merge_relationship_path(path, data) parts = path.split('.', 2) current_level = parts[0].strip data[current_level] ||= {} if parts.length == 1 # Leaf node. data[current_level].merge!({_include: true}) elsif parts.length == 2 # Need to recurse more. merge_relationship_path(parts[1], data[current_level]) end end |
.parse_relationship_paths(paths) ⇒ Object
Takes a list of relationship paths and returns a hash as deep as the given paths. The _include: true is a sentinal value that specifies whether the parent level should be included.
Example:
Given: ['author', 'comments', 'comments.user']
Returns: {
'author' => {_include: true},
'comments' => {_include: true, 'user' => {_include: true}},
}
458 459 460 461 462 |
# File 'lib/jsonapi-serializers/serializer.rb', line 458 def self.parse_relationship_paths(paths) relationships = {} paths.each { |path| merge_relationship_path(path, relationships) } relationships end |
.serialize(objects, options = {}) ⇒ Object
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/jsonapi-serializers/serializer.rb', line 226 def self.serialize(objects, = {}) # Normalize option strings to symbols. [:is_collection] = .delete('is_collection') || [:is_collection] || false [:include] = .delete('include') || [:include] [:serializer] = .delete('serializer') || [:serializer] [:context] = .delete('context') || [:context] || {} [:skip_collection_check] = .delete('skip_collection_check') || [:skip_collection_check] || false [:base_url] = .delete('base_url') || [:base_url] [:meta] = .delete('meta') || [:meta] # Normalize includes. includes = [:include] includes = (includes.is_a?(String) ? includes.split(',') : includes).uniq if includes # An internal-only structure that is passed through serializers as they are created. = { context: [:context], serializer: [:serializer], include: includes, base_url: [:base_url] } if ![:skip_collection_check] && [:is_collection] && !objects.respond_to?(:each) raise JSONAPI::Serializer::AmbiguousCollectionError.new( 'Attempted to serialize a single object as a collection.') end # Automatically include linkage data for any relation that is also included. if includes direct_children_includes = includes.reject { |key| key.include?('.') } [:include_linkages] = direct_children_includes end # Spec: Primary data MUST be either: # - a single resource object or null, for requests that target single resources. # - an array of resource objects or an empty array ([]), for resource collections. # http://jsonapi.org/format/#document-structure-top-level if [:is_collection] && !objects.any? primary_data = [] elsif ![:is_collection] && objects.nil? primary_data = nil elsif [:is_collection] # Have object collection. [:serializer] ||= find_serializer_class(objects.first) primary_data = serialize_primary_multi(objects, ) else # Duck-typing check for a collection being passed without is_collection true. # We always must be told if serializing a collection because the JSON:API spec distinguishes # how to serialize null single resources vs. empty collections. if ![:skip_collection_check] && objects.respond_to?(:each) raise JSONAPI::Serializer::AmbiguousCollectionError.new( 'Must provide `is_collection: true` to `serialize` when serializing collections.') end # Have single object. [:serializer] ||= find_serializer_class(objects) primary_data = serialize_primary(objects, ) end result = { 'data' => primary_data, } result['meta'] = [:meta] if [:meta] # If 'include' relationships are given, recursively find and include each object. if includes relationship_data = {} inclusion_tree = parse_relationship_paths(includes) # Given all the primary objects (either the single root object or collection of objects), # recursively search and find related associations that were specified as includes. objects = [:is_collection] ? objects.to_a : [objects] objects.compact.each do |obj| # Use the mutability of relationship_data as the return datastructure to take advantage # of the internal special merging logic. find_recursive_relationships(obj, inclusion_tree, relationship_data) end result['included'] = relationship_data.map do |_, data| = {} [:base_url] = [:base_url] [:serializer] = find_serializer_class(data[:object]) [:include_linkages] = data[:include_linkages] serialize_primary(data[:object], ) end end result end |
.serialize_primary(object, options = {}) ⇒ Object
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/jsonapi-serializers/serializer.rb', line 313 def self.serialize_primary(object, = {}) serializer_class = .fetch(:serializer) # Spec: Primary data MUST be either: # - a single resource object or null, for requests that target single resources. # http://jsonapi.org/format/#document-structure-top-level return if object.nil? serializer = serializer_class.new(object, ) data = { 'id' => serializer.id.to_s, 'type' => serializer.type.to_s, 'attributes' => serializer.attributes, } # Merge in optional top-level members if they are non-nil. # http://jsonapi.org/format/#document-structure-resource-objects data.merge!({'attributes' => serializer.attributes}) if !serializer.attributes.nil? data.merge!({'links' => serializer.links}) if !serializer.links.nil? data.merge!({'relationships' => serializer.relationships}) unless serializer.relationships.empty? data.merge!({'meta' => serializer.}) if !serializer..nil? data end |
.serialize_primary_multi(objects, options = {}) ⇒ Object
338 339 340 341 342 343 344 345 |
# File 'lib/jsonapi-serializers/serializer.rb', line 338 def self.serialize_primary_multi(objects, = {}) # Spec: Primary data MUST be either: # - an array of resource objects or an empty array ([]), for resource collections. # http://jsonapi.org/format/#document-structure-top-level return [] if !objects.any? objects.map { |obj| serialize_primary(obj, ) } end |