Sha256: 8929672015f8e6494d5454cb52edfbf6cfe858c6dbf5be93c858bf3b2bfe191c

Contents?: true

Size: 1.33 KB

Versions: 10

Compression:

Stored size: 1.33 KB

Contents

module JSONAPIonify::Api
  module Resource::Builders
    class RelationshipBuilder < BaseBuilder
      include IdentityHelper
      delegate :type, to: :resource, prefix: true
      delegate :request, :includes, to: :context

      attr_reader :relationship, :related_resource, :context, :instance

      def initialize(resource, relationship:, context:, instance:)
        super(resource)
        @relationship = relationship
        @context = context
        @instance = instance
        @related_resource = resource.relationship(relationship.name)
      end

      def build
        Objects::Relationship.new.tap do |rel|
          rel[:links] = related_resource.build_links(build_url)
          rel[:data] = build_data if includes.present?
        end
      end

      private

      def build_data
        rel_resource = resource.relationship(relationship.name)
        case relationship
        when Relationship::Many
          resolution.map do |child|
            rel_resource.build_resource_identifier(instance: child)
          end
        when Relationship::One
          rel_resource.build_resource_identifier instance: resolution
        end
      end

      def resolution
        instance.instance_exec(
          relationship.name,
          instance,
          context,
          &relationship.resolve
        )
      end

    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
jsonapionify-0.12.10 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.9 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.8 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.7 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.5 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.4 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.3 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.2 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.1 lib/jsonapionify/api/resource/builders/relationship_builder.rb
jsonapionify-0.12.0 lib/jsonapionify/api/resource/builders/relationship_builder.rb