Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Last active June 8, 2022 19:33
Show Gist options
  • Save julianrubisch/bcd9366f5b3343db2916f058b52e696c to your computer and use it in GitHub Desktop.
Save julianrubisch/bcd9366f5b3343db2916f058b52e696c to your computer and use it in GitHub Desktop.
class Chart < ApplicationRecord
validate do |chart|
schema = Rails.cache.fetch("vega_lite_schema/v5") do
Faraday.get("https://vega.github.io/schema/vega-lite/v5.json").body
end
JsonSchemaValidator.new(chart, schema: schema, json: vega_json, field: :vega_json).validate
end
end
require "json_schemer"
class JsonSchemaValidator
def initialize(record, schema:, json:, field:)
@record = record
@schema = schema
@json = json
@field = field
end
def validate
schemer = JSONSchemer.schema(JSON.parse(@schema))
@record.errors.add(@field, "Field #{@field} does not match JSON schema.") unless schemer.valid?(@json)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment