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
11
12
13
14
15
16
17
18
19
20
21
# 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

  # Rails 4.1 and above expose a `class` option
  if options[:class]
    inject_setter_method(options[: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(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