Sha256: 4fe96744f00dc1466a2128b99c89ddf3dbc4b27a9b8e796969fab64fc2071bb0

Contents?: true

Size: 1.8 KB

Versions: 9

Compression:

Stored size: 1.8 KB

Contents

require 'json-schema/attribute'

module JSON
  class Schema
    class AnyOfAttribute < Attribute
      def self.validate(current_schema, data, fragments, processor, validator, options = {})
        # Create a hash to hold errors that are generated during validation
        errors = Hash.new { |hsh, k| hsh[k] = [] }
        valid = false

        original_data = data.is_a?(Hash) ? data.clone : data

        current_schema.schema['anyOf'].each_with_index do |element, schema_index|
          schema = JSON::Schema.new(element,current_schema.uri,validator)

          # We're going to add a little cruft here to try and maintain any validation errors that occur in the anyOf
          # We'll handle this by keeping an error count before and after validation, extracting those errors and pushing them onto a union error
          pre_validation_error_count = validation_errors(processor).count

          begin
            schema.validate(data,fragments,processor,options)
            valid = true
          rescue ValidationError
            # We don't care that these schemas don't validate - we only care that one validated
          end

          diff = validation_errors(processor).count - pre_validation_error_count
          valid = false if diff > 0
          while diff > 0
            diff = diff - 1
            errors["anyOf ##{schema_index}"].push(validation_errors(processor).pop)
          end

          break if valid

          data = original_data
        end

        if !valid
          message = "The property '#{build_fragment(fragments)}' of type #{data.class} did not match one or more of the required schemas"
          validation_error(processor, message, fragments, current_schema, self, options[:record_errors])
          validation_errors(processor).last.sub_errors = errors
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
json-schema-2.7.0 lib/json-schema/attributes/anyof.rb
json-schema-2.6.2 lib/json-schema/attributes/anyof.rb
json-schema-2.6.1 lib/json-schema/attributes/anyof.rb
json-schema-2.6.0 lib/json-schema/attributes/anyof.rb
json-schema-2.5.2 lib/json-schema/attributes/anyof.rb
json-schema-openc-fork-0.0.2 lib/json-schema/attributes/anyof.rb
json-schema-2.5.1 lib/json-schema/attributes/anyof.rb
json-schema-openc-fork-0.0.1 lib/json-schema/attributes/anyof.rb
json-schema-2.5.0 lib/json-schema/attributes/anyof.rb