Skip to content

Passing in a fragment with an even number of tokens can lead to undefined method `validate' for #<Hash...> #265

@ckundo

Description

@ckundo

We're seeing an exception when validating a json response from a Rails controller. It seems to fail on every other token in the JSON fragment path:

schema_options = {
  fragment: "#/schemas/v1.reports.index.response/purchases",
  strict: true
}
data = JSON.parse(response.body)

JSON::Validator.fully_validate(
  "schema.json",
  data,
  schema_options,
)

Raises:

# => ...undefined method `validate' for #<Hash...>

But for example, this fragment does not raise the exception:

"#/schemas/v1.reports.index.response/purchases/items"

We have monkey-patched this as follows:

module JSON
  class Validator
    def schema_from_fragment(base_schema, fragment)
      # ...

      fragments.each do |f|
        if base_schema.is_a?(JSON::Schema) #test if fragment is a JSON:Schema instance
          if !base_schema.schema.has_key?(f)
            raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
          end

          # HERE:
          if base_schema.schema[f].is_a? Hash
            base_schema = JSON::Schema.new(base_schema.schema[f], schema_uri, @options[:version])
          else
            base_schema = base_schema.schema[f]
          end
        elsif base_schema.is_a?(Hash)
          # ...

That is, this line https://github.com/ruby-json-schema/json-schema/blob/master/lib/json-schema/validator.rb#L91 should always create a new JSON::Schema.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions