Class: JsonSchemaValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- JsonSchemaValidator
- Defined in:
- app/validators/json_schema_validator.rb
Overview
This Rails validator checks that an attribute is either a valid JSON schema or that it complies with a given schema.
Constant Summary collapse
- NAMED_SCHEMA_VERSIONS =
i[draft201909 draft202012 draft4 draft6 draft7 openapi30 openapi31].freeze
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'app/validators/json_schema_validator.rb', line 8 def validate_each(record, attribute, value) # Convert value to hash if it's a string json_data = value.is_a?(String) ? JSON.parse(value) : value # Get the schema from options, evaluating lambda if provided schema = resolve_schema(record, attribute, value) # Initialize JSONSchemer with proper handling based on schema type schemer = json_schemer(schema) # Collect validation errors validation_errors = schemer.validate(json_data).to_a # Add errors to the record using json_schemer's built-in I18n support validation_errors.each do |error| record.errors.add(attribute, error['error']) end rescue JSON::ParserError record.errors.add(attribute, :invalid_json) end |