davishmcclurg / json_schemer

JSON Schema validator. Supports drafts 4, 6, 7, 2019-09, 2020-12, OpenAPI 3.0, and OpenAPI 3.1.
MIT License
408 stars 64 forks source link

Schema#ref does not apply custom configuration options #198

Open ahx opened 2 weeks ago

ahx commented 2 weeks ago

Hi. What I would like to do is to use insert_property_defaults: true for subschemas that are adressed via Schema#ref without globally changing JSONSchemer.configuration. But currently that does not seem to be possible, because Schema#ref does not apply the custom local options, but only uses the global configuration and passing insert_property_defaults: true to Schema#validate is not supported.

Here is an example:

doc = JSONSchemer.openapi(contents, insert_property_defaults: true)
content_schema = doc.ref('/components/schemas/MySchema')
content_schema.validate(data) # Fails, because insert_property_defaults is not applied (false)
# Now this (hack) makes it apply the option, but also changes global configuration, which I don't want:
doc = JSONSchemer.openapi(contents,)
content_schema = doc.ref('/components/schemas/MySchema')
content_schema.configuration.insert_property_defaults = true
content_schema.validate(data) # Succeeds

puts JSONSchemer.configuration.insert_property_defaults # => true

If you have a suggestion for an API to solve this, I'd be happy to try to create a PR for that.

ahx commented 2 weeks ago

Ha! I've found a solution.

  configuration = JSONSchemer::Configuration.new(insert_property_defaults: true)
  doc = JSONSchemer.openapi(resolved, configuration:)
  content_schema = doc.ref('/components/schemas/MySchema')
  content_schema.validate(data) # Succeeds! 

Thanks! 🦆 Feel free to close this issue.