Module: Pupa::Refinements::FormatAttribute

Included in:
JSON::Schema::FormatAttribute
Defined in:
lib/pupa/refinements/json-schema.rb

Overview

Validates "email" and "uri" formats. Using Ruby's refinements doesn't seem to work, possibly because refine can't be used with prepend.

Instance Method Summary collapse

Instance Method Details

#validate(current_schema, data, fragments, processor, validator, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pupa/refinements/json-schema.rb', line 9

def validate(current_schema, data, fragments, processor, validator, options = {})
  case current_schema.schema['format']
  when 'email'
    if String === data
      address = Mail::Address.new(data)
      unless address.address == data && address.domain && address.domain.split('.').size > 1
        error_message = "The property '#{build_fragment(fragments)}' must be a valid email address (#{data})"
        validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors])
      end
    else
      error_message = "The property '#{build_fragment(fragments)}' must be a string (#{data})"
      validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors])
    end
  when 'uri'
    if String === data
      re = URI::DEFAULT_PARSER.regexp[:ABS_URI]
      unless re.match(data)
        error_message = "The property '#{build_fragment(fragments)}' must be a valid URI (#{data})"
        validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors])
      end
    else
      error_message = "The property '#{build_fragment(fragments)}' must be string (#{data})"
      validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors])
    end
  else
    super
  end
end