Sha256: 006b2134aa1c80e58f7f69b44579f6117eda93bcc71bc7880f00d753ba067823

Contents?: true

Size: 1.73 KB

Versions: 7

Compression:

Stored size: 1.73 KB

Contents

# typed: false

module Mangadex
  module Internal
    module Definitions
      class Accepts
        VALID_CONDITIONS = [:and, :or]

        class Possibility
          def initialize(accepted:)
            @accepted = accepted
          end

          def inspect
            "{#{@accepted.class.name}: #{@accepted}}"
          end
        end

        def initialize(array: nil, class: nil, value: nil, condition: :and)
          @array = array
          @class = binding.local_variable_get(:class)
          @value = value
          @condition = ensure_valid_condition!(condition.to_s.to_sym)
        end

        def validate!(value)
          valid = if @condition == :or
            validate_or!(value)
          else
            validate_and!(value)
          end

          raise ArgumentError, "Value `#{value}` must be #{nature}: #{possibilities}" unless valid
        end

        private

        def ensure_valid_condition!(condition)
          return condition if VALID_CONDITIONS.include?(condition)

          raise "Condition `#{condition}` must be one of #{VALID_CONDITIONS}"
        end

        def nature
          @condition == :or ? "one of" : "all of"
        end

        def validate_and!(value)
          possibilities.all? { potentially_valid?(value) }
        end

        def validate_or!(value)
          possibilities.any? { potentially_valid?(value) }
        end

        def possibilities
          @possibilities ||= [
            @array,
            @class,
            @value,
          ].compact.map { |pos| Possibility.new(accepted: pos) }
        end

        def potentially_valid?(value)
          @array.include?(value) || \
            value.is_a?(@class) || \
            value == @value
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
mangadex-5.10.0 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.9.0 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.8.0 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.7.5.3 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.7.5.2 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.7.5.1 lib/mangadex/internal/definitions/accepts.rb
mangadex-5.7.5 lib/mangadex/internal/definitions/accepts.rb