Sha256: 23f9f7d09536d69b3f131106f8fcbbc16b52ff69574e1f0312a7132a010b62b8
Contents?: true
Size: 1.7 KB
Versions: 2
Compression:
Stored size: 1.7 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:) @camel_fields = {} @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) next if relations.nil? 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| key = @camel_fields[field] ||= key_transform(field) hash[key] = 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
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
zuora_connect_ui-0.11.5 | lib/zuora_connect_ui/serializer/relationship.rb |
zuora_connect_ui-0.11.4 | lib/zuora_connect_ui/serializer/relationship.rb |