Sha256: 42b4d6c0a3d22b9c86ddac72979e12383d3a0dbd64a2bcb28da948a6bb90fae0

Contents?: true

Size: 1.03 KB

Versions: 10

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

module MediaTypes
  class Scheme
    class Attribute

      ##
      # An attribute that expects a value of type +type+
      #
      # @see AllowNil
      # @see AnyOf
      #
      # @param [Class] type the class +it+ must be
      # @param [TrueClass, FalseClass] allow_nil if true, nil? is allowed
      #
      def initialize(type, allow_nil: false)
        self.type = type
        self.allow_nil = allow_nil

        freeze
      end

      def validate!(output, options, **_opts)
        if output.nil?
          return true if allow_nil
        end

        return true if type === output # rubocop:disable Style/CaseEquality
        raise ValidationError,
              format(
                'Expected %<type>s, got %<actual>s at [%<backtrace>s]',
                type: type,
                actual: output.inspect,
                backtrace: options.backtrace.join('->')
              )
      end

      private

      attr_accessor :allow_nil, :type

    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
media_types-0.4.1 lib/media_types/scheme/attribute.rb
media_types-0.4.0 lib/media_types/scheme/attribute.rb
media_types-0.3.0 lib/media_types/scheme/attribute.rb
media_types-0.2.6 lib/media_types/scheme/attribute.rb
media_types-0.2.5 lib/media_types/scheme/attribute.rb
media_types-0.2.4 lib/media_types/scheme/attribute.rb
media_types-0.2.3 lib/media_types/scheme/attribute.rb
media_types-0.2.2 lib/media_types/scheme/attribute.rb
media_types-0.2.1 lib/media_types/scheme/attribute.rb
media_types-0.2.0 lib/media_types/scheme/attribute.rb