Class: JsonSchemaValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- JsonSchemaValidator
- Defined in:
- app/validators/json_schema_validator.rb
Overview
JsonSchemaValidator
Custom validator for json schema. Create a json schema within the json_schemas directory
class Project < ActiveRecord::Base
validates :data, json_schema: { filename: "file", size_limit: 64.kilobytes }
end
Constant Summary collapse
- FILENAME_ALLOWED =
/\A[a-z0-9_-]*\Z/- FilenameError =
Class.new(StandardError)
- BASE_DIRECTORY =
%w[app validators json_schemas].freeze
Instance Method Summary collapse
-
#initialize(options) ⇒ JsonSchemaValidator
constructor
A new instance of JsonSchemaValidator.
- #schema ⇒ Object
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ JsonSchemaValidator
Returns a new instance of JsonSchemaValidator.
18 19 20 21 22 23 24 25 26 |
# File 'app/validators/json_schema_validator.rb', line 18 def initialize() raise ArgumentError, "Expected 'filename' as an argument" unless [:filename] raise FilenameError, "Must be a valid 'filename'" unless [:filename].match?(FILENAME_ALLOWED) @base_directory = .delete(:base_directory) || BASE_DIRECTORY @size_limit = .delete(:size_limit) super() end |
Instance Method Details
#schema ⇒ Object
47 48 49 |
# File 'app/validators/json_schema_validator.rb', line 47 def schema @schema ||= JSONSchemer.schema(schema_path) end |
#validate_each(record, attribute, value) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'app/validators/json_schema_validator.rb', line 28 def validate_each(record, attribute, value) value = Gitlab::Json.parse(Gitlab::Json.dump(value)) if [:hash_conversion] == true value = Gitlab::Json.parse(value.to_s) if [:parse_json] == true && !value.nil? if size_limit && !valid_size?(value) record.errors.add(attribute, ) return end if [:detail_errors] schema.validate(value).each do |error| = (error) record.errors.add(attribute, ) end else record.errors.add(attribute, ) unless valid_schema?(value) end end |