Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions lib/json/schema_builder/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def initialize(name, opts = { }, &block)
initialize_parent_with opts
initialize_with opts
eval_block &block
any_of(null) if @nullable
extract_types
@initialized = true
end
Expand Down Expand Up @@ -138,13 +139,16 @@ def _reset_fragments
end

def extract_types
any_of(null) if @nullable
if any_of.present?
everything_else = schema.data.reject { |k, v| k == "anyOf" }
return unless everything_else.present?
schema.data.select! { |k, v| k == "anyOf" }
schema.data["anyOf"].unshift everything_else
return unless any_of.present?
everything_else = schema.data.reject { |k, v| k == "anyOf" }
return unless everything_else.present?
schema.data.select! { |k, v| k == "anyOf" }
if initial = schema.data['anyOf'].find { |opt| opt.as_json.try(:[], 'type') == 'object' }
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume that, when some is extending this, they intend to extend the object, not the null, so I extract the initial definition and extend it here. This is really ugly right now though and probably won't work in some cases. Happy for any comments here.

initial.deep_merge! everything_else.as_json
else
schema.data["anyOf"].unshift everything_else
end
schema.data["anyOf"].uniq!
end

def initialize_parent_with(opts)
Expand Down
15 changes: 15 additions & 0 deletions spec/integration/builder_initialization_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@
}
}
},
target: {
anyOf: [
{
type: :object,
properties: {
id: {
type: :number
}
}
},
{
type: :null
}
]
},
preferences: {
anyOf: [
{
Expand Down
15 changes: 15 additions & 0 deletions spec/integration/builder_reopening_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@
}
}
},
target: {
anyOf: [
{
type: :object,
properties: {
id: {
type: :number
}
}
},
{
type: :null
}
]
},
preferences: {
anyOf: [
{
Expand Down
7 changes: 7 additions & 0 deletions spec/support/examples/builder_initialization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,18 @@ def example
obj = object
obj.string :name
settings_for(obj)
target_for(obj)
preferences_for(obj)
add_ids_to(obj)
obj
end

def target_for(obj)
target = obj.object :target, null: true
target.number :id
target
end

def settings_for(obj)
settings = obj.object :settings
settings.string :email
Expand Down