Class: JsonValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- JsonValidator
- Defined in:
- lib/active_record/json_validator/validator.rb
Instance Method Summary collapse
-
#initialize(options) ⇒ JsonValidator
constructor
A new instance of JsonValidator.
-
#validate_each(record, attribute, value) ⇒ Object
Validate the JSON value with a JSON schema path or String.
Constructor Details
#initialize(options) ⇒ JsonValidator
Returns a new instance of JsonValidator.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/active_record/json_validator/validator.rb', line 2 def initialize() .reverse_merge!(message: :invalid_json) .reverse_merge!(schema: nil) @attributes = [:attributes] super # Rails 4.1 and above expose a `class` option if [:class] inject_setter_method([:class], @attributes) # Rails 4.0 and below calls a `#setup` method elsif !respond_to?(:setup) class_eval do define_method :setup do |model| inject_setter_method(model, @attributes) end end end end |
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
Validate the JSON value with a JSON schema path or String
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/active_record/json_validator/validator.rb', line 24 def validate_each(record, attribute, value) begin json_value = JSON.dump(value) rescue JSON::GeneratorError json_value = '' end errors = ::JSON::Validator.fully_validate(.fetch(:schema), json_value) if errors.any? || instance_variable_get(:"@_#{attribute}_sane_json") == false record.errors.add(attribute, .fetch(:message), value: value) end end |