Class: JsonValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_record/json_validator/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ JsonValidator

Returns a new instance of JsonValidator.



2
3
4
5
6
7
8
9
10
# File 'lib/active_record/json_validator/validator.rb', line 2

def initialize(options)
  options.reverse_merge!(message: :invalid_json)
  options.reverse_merge!(schema: nil)
  @attributes = options[:attributes]

  super

  inject_setter_method(options[:class], @attributes) if options[:class]
end

Instance Method Details

#setup(model) ⇒ Object

Only respond to #setup if we’re in Rails 4.0 or less



13
14
15
# File 'lib/active_record/json_validator/validator.rb', line 13

def setup(model)
  inject_setter_method(model, @attributes)
end

#validate_each(record, attribute, value) ⇒ Object

Validate the JSON value with a JSON schema path or String



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/active_record/json_validator/validator.rb', line 18

def validate_each(record, attribute, value)
  begin
    json_value = JSON.dump(value)
  rescue JSON::GeneratorError
    json_value = ''
  end

  errors = ::JSON::Validator.fully_validate(options.fetch(:schema), json_value)

  if errors.any? || instance_variable_get(:"@_#{attribute}_sane_json") == false
    record.errors.add(attribute, options.fetch(:message), value: value)
  end
end