class J2119::FieldTypeConstraint

Verify type of a field in a node

Public Class Methods

new(name, type, is_array, is_nullable) click to toggle source
Calls superclass method J2119::Constraint::new
# File lib/j2119/constraints.rb, line 130
def initialize(name, type, is_array, is_nullable)
  super()
  @name = name
  @type = type
  @is_array = is_array
  @is_nullable = is_nullable
end

Public Instance Methods

check(node, path, problems) click to toggle source
# File lib/j2119/constraints.rb, line 144
def check(node, path, problems)

  # type-checking is orthogonal to existence checking
  return if !node.key?(@name)

  value = node[@name]
  path = "#{path}.#{@name}"

  if value == nil
    if !@is_nullable
      problems << "#{path} should be non-null"
    end
    return
  end

  if @is_array
    if value.is_a?(Array)
      i = 0
      value.each do |element|
        value_check(element, "#{path}[#{i}]", problems)
        i += 1
      end
    else
      report(path, value, 'an Array', problems)
    end
  else
    value_check(value, path, problems)
  end
end
report(path, value, message, problems) click to toggle source
# File lib/j2119/constraints.rb, line 210
def report(path, value, message, problems)
  if value.is_a?(String)
    value = '"' + value + '"'
  end
  problems << "#{path} is #{value} but should be #{message}"
end
to_s() click to toggle source
# File lib/j2119/constraints.rb, line 138
def to_s
  conds = (@conditions.empty?) ? '' : " #{@conditions.size} conditions"
  nullable = @is_nullable ? ' (nullable)' : ''
  "<Field #{@name} should be of type #{@type}#{conds}>#{nullable}"
end
value_check(value, path, problems) click to toggle source
# File lib/j2119/constraints.rb, line 174
def value_check(value, path, problems)
  case @type
  when :object
    report(path, value, 'an Object', problems) if !value.is_a?(Hash)
  when :array
    report(path, value, 'an Array', problems) if !value.is_a?(Array)
  when :string
    report(path, value, 'a String', problems) if !value.is_a?(String)
  when :integer
    report(path, value, 'an Integer', problems) if !value.is_a?(Integer)
  when :float
    report(path, value, 'a Float', problems) if !value.is_a?(Float)
  when :boolean
    if value != true && value != false
      report(path, value, 'a Boolean', problems)
    end
  when :numeric
    report(path, value, 'numeric', problems) if !value.is_a?(Numeric)
  when :json_path
    report(path, value, 'a JSONPath', problems) if !JSONPathChecker.is_path?(value)
  when :reference_path
    report(path, value, 'a Reference Path', problems) if !JSONPathChecker.is_reference_path?(value)
  when :timestamp
    begin
      DateTime.rfc3339 value
    rescue
      report(path, value, 'an RFC3339 timestamp', problems)
    end
  when :URI
    if !(value.is_a?(String) && (value =~ /^[a-z]+:/))
      report(path, value, 'A URI', problems) 
    end
  end
  
end