module HasJsonSchema

Public Class Methods

create_json_schema_validations(schema_field_name) click to toggle source
# File lib/buweb/concerns/has_json_schema.rb, line 5
def self.create_json_schema_validations(schema_field_name)
  writer_name = "#{schema_field_name}="

  # Creates writer method that validates and beautifies the json before saving
  # def json_schema=(json)
  define_method(writer_name) do |json|
    begin
      # Write attribute before anything else in case it fails we don't loose changes in editor
      write_attribute(schema_field_name, json)

      if json.present?
        # Parse json to validate. It will raise an error if the JSON is not valid
        schema_object = JSON.parse(json)
        # This only checks if it is valid JSON, eventually we might validate it
        # against the json-schema spec.

        # Set json-schema draft version if it is not set
        schema_object["$schema"] ||= "http://json-schema.org/draft-04/schema#"

        # Re-save pretty and valid json
        write_attribute(schema_field_name, JSON.pretty_generate(schema_object))
      end
    rescue JSON::ParserError
      # You can't add errors here, it needs to be done in a separate validator that is called
      # during the validation callback.
      return false
    end
  end

  # def validate_json_schema
  define_method(:validate_json_schema) do
    begin
      json = read_attribute(schema_field_name)
      # Parse json to validate
      # Don't try to parse if it is blank, that would fail,
      #   but it should be allowed
      JSON.parse(json) if json.present?
    rescue JSON::ParserError
      # Add error to base so it doesn't mess up code editor
      errors.add(:base, "Schema is not valid JSON")
      return false
    end
  end
end