Sha256: b553a231c6850b34c23e6e71749afc14d968c3a1b30b07e60b305f4fffc24556
Contents?: true
Size: 1.59 KB
Versions: 4
Compression:
Stored size: 1.59 KB
Contents
# 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 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
Version data entries
4 entries across 4 versions & 1 rubygems