Method: JSONSchemer::Result#insert_property_defaults

Defined in:
lib/json_schemer/result.rb

#insert_property_defaults(context) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/json_schemer/result.rb', line 181

def insert_property_defaults(context)
  instance_locations = {}
  instance_locations.compare_by_identity

  results = [[self, true]]
  while (result, valid = results.pop)
    next if result.source.is_a?(Schema::NOT_KEYWORD_CLASS)

    valid &&= result.valid
    result.nested&.each { |nested_result| results << [nested_result, valid] }

    if result.source.is_a?(Schema::PROPERTIES_KEYWORD_CLASS) && result.instance.is_a?(Hash)
      result.source.parsed.each do |property, schema|
        next if result.instance.key?(property)
        next unless default = default_keyword_instance(schema)
        instance_location = Location.join(result.instance_location, property)
        keyword_location = Location.join(Location.join(result.keyword_location, property), default.keyword)
        default_result = default.validate(nil, instance_location, keyword_location, nil)
        instance_locations[result.instance_location] ||= {}
        instance_locations[result.instance_location][property] ||= []
        instance_locations[result.instance_location][property] << [default_result, valid]
      end
    end
  end

  inserted = false

  instance_locations.each do |instance_location, properties|
    original_instance = context.original_instance(instance_location)
    properties.each do |property, results_with_tree_validity|
      property_inserted = yield(original_instance, property, results_with_tree_validity)
      inserted ||= (property_inserted != false)
    end
  end

  inserted
end