# frozen_string_literal: true module ZuoraConnectUi class Serializer # The configuration for a relationship between models class Relationship # key may be plural, record_type will always be singular attr_reader :key, :relationship_type, :id_method_name, :record_type, :plural_type def initialize(key:, relationship_type:) @key = key @relationship_type = relationship_type set_id_method_name end def serialize(resources, fields) resources.each_with_object({}) do |resource, hash| relations = resource.public_send(key) relations = [relations] unless @relationship_type == :has_many relations.each do |relation| next if hash.key? relation.id.to_s.to_sym hash[relation.id.to_s.to_sym] = record_hash(relation, fields) end end end private def record_hash(resource, fields) hash = { id: resource.id } fields.each do |field| hash[key_transform(field)] = resource.public_send(field) end hash end def set_id_method_name if @relationship_type == :has_many singular_key = @key.to_s.singularize id_postfix = '_ids' else singular_key = @key.to_s id_postfix = '_id' end @record_type = singular_key.to_sym @plural_type = singular_key.pluralize.to_sym @id_method_name = "#{singular_key}#{id_postfix}".to_sym end def key_transform(input) input.to_s.camelize(:lower).to_sym end end end end