Sha256: 8d420e3aa0505f297c78a36fb13d5f739c3bf78469b5243e71fed5d79356a83e

Contents?: true

Size: 1.71 KB

Versions: 9

Compression:

Stored size: 1.71 KB

Contents

module JsonapiCompliable
  module Util
    # Helper methods for traversing the 'relationships' JSONAPI payloads
    # @api private
    class RelationshipPayload
      attr_reader :resource, :payload

      def self.iterate(resource:, relationships: {}, only: [], except: [])
        instance = new(resource, relationships, only: only, except: except)
        instance.iterate do |sideload, relationship_data, sub_relationships|
          yield sideload, relationship_data, sub_relationships
        end
      end

      def initialize(resource, payload, only: [], except: [])
        @resource = resource
        @payload  = payload
        @only     = only
        @except   = except
      end

      def iterate
        payload.each_pair do |relationship_name, relationship_payload|
          if sl = resource.sideload(relationship_name.to_sym)
            if should_yield?(sl.type)
              if relationship_payload.is_a?(Array)
                relationship_payload.each do |rp|
                  yield payload_for(sl, rp)
                end
              else
                yield payload_for(sl, relationship_payload)
              end
            end
          end
        end
      end

      private

      def should_yield?(type)
        (@only.length > 0 && @only.include?(type)) ||
          (@except.length > 0 && !@except.include?(type))
      end

      def payload_for(sideload, relationship_payload)
        {
          sideload: sideload,
          primary_key: sideload.primary_key,
          foreign_key: sideload.foreign_key,
          attributes: relationship_payload[:attributes],
          meta: relationship_payload[:meta],
          relationships: relationship_payload[:relationships]
        }
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
jsonapi_compliable-0.6.13 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.12 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.11 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.10 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.9 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.8 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.7 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.6 lib/jsonapi_compliable/util/relationship_payload.rb
jsonapi_compliable-0.6.5 lib/jsonapi_compliable/util/relationship_payload.rb