Class: JsonValidator

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

Constant Summary collapse

VERSION =
JsonValidatorMeta::VERSION

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



42
43
44
# File 'lib/json_validator.rb', line 42

def check_validity!
  fail ArgumentError, :'Schema unspecified. Please specify :schema as either a Proc or a hash' if options[:schema].nil?
end

#json(value) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/json_validator.rb', line 29

def json(value)
  if value.respond_to?(:to_hash)
    value.to_hash
  else
    JSON.parse(value.to_s)
  end
end

#schema(record) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/json_validator.rb', line 21

def schema(record)
  if options[:schema].respond_to?(:call)
    options[:schema].call(record)
  else
    options[:schema].to_hash
  end
end

#translate_message(msg) ⇒ Object



37
38
39
40
# File 'lib/json_validator.rb', line 37

def translate_message(msg)
  # remove suffix
  msg.gsub!(/ in schema .*$/, '')
end

#validate_each(record, attribute, value) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/json_validator.rb', line 11

def validate_each(record, attribute, value)
  raw_errors = JSON::Validator.fully_validate(schema(record), json(value))
  translated_errors = raw_errors.map do |e|
    translate_message(e)
  end
  translated_errors.each do |e|
    record.errors.add(attribute, e)
  end
end