class JsonValidator
Constants
- VERSION
Public Instance Methods
check_validity!()
click to toggle source
# File lib/json_validator.rb, line 46 def check_validity! fail ArgumentError, :'Schema unspecified. Please specify :schema as either a Proc or a hash' if options[:schema].nil? end
json(value)
click to toggle source
# 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)
click to toggle source
# 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)
click to toggle source
# File lib/json_validator.rb, line 37 def translate_message(msg) # remove suffix msg.gsub!(/ in schema .*$/, '') # lowercase first letter (eg. 'The' becomes 'the') msg.gsub!(/^./) { |m| m.downcase } # prefix with 'is invalid' msg.gsub!(/^(.*)$/, 'is invalid (\1)') end
validate_each(record, attribute, value)
click to toggle source
# 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