Adds documentations for RelationshipSchemaGenerator

This commit is contained in:
Muhammad Nawzad 2023-11-17 16:45:57 +03:00
parent 04f7ded55d
commit f4f273428f
No known key found for this signature in database
GPG Key ID: B954B6AAE33940B2

View File

@ -1,13 +1,35 @@
module Schemable
# The RelationshipSchemaGenerator class is responsible for generating the 'relationships' part of a JSON:API compliant response.
# This class generates schemas for each relationship of a model, including 'belongs_to' (and has_many) and 'has_many' relationships.
#
# @see Schemable
class RelationshipSchemaGenerator
attr_reader :model_definition, :schema_modifier, :relationships
# Initializes a new RelationshipSchemaGenerator instance.
#
# @param model_definition [ModelDefinition] The model definition to generate the schema for.
#
# @example
# generator = RelationshipSchemaGenerator.new(model_definition)
def initialize(model_definition)
@model_definition = model_definition
@schema_modifier = SchemaModifier.new
@relationships = model_definition.relationships
end
# Generates the 'relationships' part of the JSON:API response.
# It iterates over each relationship type (belongs_to, has_many) and for each relationship,
# it prepares a schema unless the relationship is excluded from expansion.
# If the 'expand' option is true, it changes the schema to include type and id properties inside the 'meta' property.
#
# @param relationships_to_exclude_from_expansion [Array] The relationships to exclude from expansion.
# @param expand [Boolean] Whether to include the relationships of the related resource in the schema.
#
# @example
# schema = generator.generate(expand: true, relationships_to_exclude_from_expansion: [:some_relationship])
#
# @return [Hash] The generated schema.
def generate(relationships_to_exclude_from_expansion: [], expand: false)
return {} if @relationships.blank? || @relationships == { belongs_to: {}, has_many: {} }
@ -49,6 +71,18 @@ module Schemable
schema
end
# Generates the schema for a specific relationship.
# If the 'collection' option is true, it generates a schema for a 'has_many' relationship,
# otherwise it generates a schema for a 'belongs_to' relationship. The difference between the two is that
# 'data' is an array in the 'has_many' relationship and an object in the 'belongs_to' relationship.
#
# @param type_name [String] The type of the related resource.
# @param collection [Boolean] Whether the relationship is a 'has_many' relationship.
#
# @example
# relationship_schema = generator.generate_schema('resource_type', collection: true)
#
# @return [Hash] The generated schema for the relationship.
def generate_schema(type_name, collection: false)
if collection
{