Sha256: 93fe045915ae0e5e8c356bf42731cc82b657bb6a22cdac18e78bda4d50c07a59

Contents?: true

Size: 1.74 KB

Versions: 9

Compression:

Stored size: 1.74 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)
        relationship_hash = {}

        resources.each do |resource|
          relations = resource.public_send(key)

          next if relations.nil?

          relations = [relations] unless @relationship_type == :has_many

          relations.each do |relation|
            next if relationship_hash.key? relation.id

            relationship_hash[relation.id] = record_hash(relation, fields)
          end
        end

        relationship_hash
      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

9 entries across 9 versions & 1 rubygems

Version Path
zuora_connect_ui-0.12.3 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.12.2 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.12.1 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.12.0 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.11.10 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.11.9 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.11.8 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.11.7 lib/zuora_connect_ui/serializer/relationship.rb
zuora_connect_ui-0.11.6 lib/zuora_connect_ui/serializer/relationship.rb