lib/schemacop/v3/node.rb in schemacop-3.0.28 vs lib/schemacop/v3/node.rb in schemacop-3.0.29
- old
+ new
@@ -190,10 +190,25 @@
json[:require_key] = @require_key if @require_key
return json.as_json
end
+ def parse_if_json(data, allowed_types:, result: nil)
+ if data.is_a?(String)
+ data = JSON.parse(data)
+
+ if result && !validate_type(data, result, allowed_types: allowed_types)
+ return nil
+ end
+ end
+
+ return data
+ rescue JSON::ParserError => e
+ result&.error "JSON parse error: #{e.message.inspect}."
+ return nil
+ end
+
def type_assertion_method
:is_a?
end
def _validate(data, result:)
@@ -211,21 +226,27 @@
data = default
end
end
# Validate type #
- if allowed_types.any? && allowed_types.keys.none? { |c| data.send(type_assertion_method, c) }
- collection = allowed_types.values.map { |t| "\"#{t}\"" }.uniq.sort.join(' or ')
- result.error "Invalid type, got type \"#{data.class}\", expected #{collection}."
- return nil
- end
+ return nil unless validate_type(data, result)
# Validate enums #
if @enum && !@enum.include?(data)
result.error "Value not included in enum #{@enum.to_a.inspect}."
end
return data
+ end
+
+ def validate_type(data, result, allowed_types: self.allowed_types)
+ if allowed_types.any? && allowed_types.keys.none? { |c| data.send(type_assertion_method, c) }
+ collection = allowed_types.values.map { |t| "\"#{t}\"" }.uniq.sort.join(' or ')
+ result.error "Invalid type, got type \"#{data.class}\", expected #{collection}."
+ return false
+ end
+
+ return true
end
def validate_self; end
end
end