notEthan / jsi

JSI: JSON Schema Instantiation in Ruby
Other
22 stars 1 forks source link

Feature request: composing JSI objects #335

Open unj1m opened 4 months ago

unj1m commented 4 months ago

FWIW, I find myself wanting to compose JSI objects by having JSI objects in hashes where sub-hashes are expected.

I would use this for complex structures where I want to build the components by creating and validating JSI objects.

Instead, I end up creating and validating JSI objects and then having to convert them back to hashes ('as_json'), to build the larger structures.

Not the end of the world, but a bit awkward.

Having said that, thanks for JSI. :smile:

notEthan commented 4 months ago

I have also found myself doing that a time or two. The difficulty resolving this is in what schemas apply. For example, given an instance like {"foo" => {}}

root_schema = JSI.new_schema({
  "$schema" => "http://json-schema.org/draft-07/schema#",
  "properties" => {
    "foo" => {"title" => "root/foo"}
  },
})

foo_schema = JSI.new_schema({
  "$schema" => "http://json-schema.org/draft-07/schema#",
  "title" => "foo",
})

foo = foo_schema.new_jsi({})
root = root_schema.new_jsi({"foo" => foo})

Then what schemas end up describing root.foo? It could be a root_schema.properties['foo'] or a foo_schema, or possibly both. (it could even be a foo_schema as the instance inside of a root_schema.properties['foo'] but that seems very confusing).

I don't know that that resembles your use case - maybe your descendent hashes are described by the same schemas that the root schema indicates, but it is a thing that I'd need to resolve.

My inclination is to just recursively strip instances of any schemas in new_jsi, so root.foo above would be a root_schema.properties['foo'] and not a foo_schema. This is consistent with Base#[]= and attribute writer methods, which discard any schemas (i.e. after root.foo = foo, root.foo is not a foo_schema). Would that match what you'd expect? I have slight hesitation on discarding schemas from what has been given, but it seems like the best answer.

Thanks for your interest and feedback.