Sha256: 10f4c2a354a88809073ece2bb05251a906d5f7c4eaecbeec434188e3e3d529a7

Contents?: true

Size: 1.19 KB

Versions: 5

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module LedgerSync
  module Type
    class ReferenceMany < Value # :nodoc:
      include ValueMixin

      attr_reader :resource_class

      def initialize(resource_class:)
        @resource_class = resource_class
        super()
      end

      def error_message(attribute:, resource:, value:)
        return super unless value.is_a?(Array)

        invalid_classes = value.reject { |e| e.is_a?(resource_class) }.map(&:class)
        "Attribute #{attribute.name} for #{resource.class.name} should be an array of #{resource_class.name}.  Given array containing: #{invalid_classes.join(', ')}"
      end

      def type
        :reference_many
      end

      def valid_without_casting?(value:)
        return false unless value.is_a?(Array)
        return true if (resource_classes & value.map(&:class)).any?
        return true if value.is_a?(Array) && value.empty?

        false
      end
      private

      def resource_classes
        @resource_classes ||= if resource_class.is_a?(Array)
                                resource_class
                              else
                                [resource_class]
                              end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ledger_sync-1.3.5 lib/ledger_sync/type/reference_many.rb
ledger_sync-1.3.4 lib/ledger_sync/type/reference_many.rb
ledger_sync-1.3.3 lib/ledger_sync/type/reference_many.rb
ledger_sync-1.3.2 lib/ledger_sync/type/reference_many.rb
ledger_sync-1.3.1 lib/ledger_sync/type/reference_many.rb