Sha256: 588bf98e01f72ec66264e06b3212d8e5c783b23a2afc414943073fb96e844002

Contents?: true

Size: 1.93 KB

Versions: 7

Compression:

Stored size: 1.93 KB

Contents

# frozen_string_literal: true

require 'active_model/serializer/lazy_association'

module ActiveModel
  class Serializer
    # This class holds all information about serializer's association.
    #
    # @api private
    Association = Struct.new(:reflection, :association_options) do
      attr_reader :lazy_association
      delegate :object, :include_data?, :virtual_value, :collection?, to: :lazy_association

      def initialize(*)
        super
        @lazy_association = LazyAssociation.new(reflection, association_options)
      end

      # @return [Symbol]
      delegate :name, to: :reflection

      # @return [Symbol]
      def key
        reflection_options.fetch(:key, name)
      end

      # @return [True,False]
      def key?
        reflection_options.key?(:key)
      end

      # @return [Hash]
      def links
        reflection_options.fetch(:links) || {}
      end

      # @return [Hash, nil]
      # This gets mutated, so cannot use the cached reflection_options
      def meta
        reflection.options[:meta]
      end

      def belongs_to?
        reflection.foreign_key_on == :self
      end

      def polymorphic?
        true == reflection_options[:polymorphic]
      end

      # @api private
      def serializable_hash(adapter_options, adapter_instance)
        association_serializer = lazy_association.serializer
        return virtual_value if virtual_value
        association_object = association_serializer && association_serializer.object
        return unless association_object

        serialization = association_serializer.serializable_hash(adapter_options, {}, adapter_instance)

        if polymorphic? && serialization
          polymorphic_type = association_object.class.name.underscore
          serialization = { type: polymorphic_type, polymorphic_type.to_sym => serialization }
        end

        serialization
      end

      private

      delegate :reflection_options, to: :lazy_association
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
active_model_serializers-0.10.15 lib/active_model/serializer/association.rb
active_model_serializers-0.10.14 lib/active_model/serializer/association.rb
active_model_serializers-0.10.13 lib/active_model/serializer/association.rb
active_model_serializers-0.10.12 lib/active_model/serializer/association.rb
active_model_serializers-0.10.11 lib/active_model/serializer/association.rb
active_model_serializers-0.10.10 lib/active_model/serializer/association.rb
active_model_serializers-0.10.9 lib/active_model/serializer/association.rb