Module: SchemaTools::Modules::Validations::ClassMethods

Defined in:
lib/schema_tools/modules/validations.rb

Instance Method Summary collapse

Instance Method Details

#validate_length_opts(attr) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/schema_tools/modules/validations.rb', line 57

def validate_length_opts(attr)
  opts = {}
  opts[:within] = attr['minLength']..attr['maxLength'] if attr['minLength'] && attr['maxLength']
  opts[:maximum] = attr['maxLength'] if attr['maxLength'] && !attr['minLength']
  opts[:minimum] = attr['minLength'] if attr['minLength'] && !attr['maxLength']
  opts[:allow_blank] = true if !attr['required']
  opts
end

#validate_number_opts(attr) ⇒ Object

Parameters:

  • attr (Hash<String>)

    property values



67
68
69
70
71
72
73
74
75
76
# File 'lib/schema_tools/modules/validations.rb', line 67

def validate_number_opts(attr)
  opts = {}
  opts[:allow_blank] = true
  # those vals should not be set both in one property
  opts[:greater_than_or_equal_to] = attr['minimum'] if attr['minimum'].present?
  opts[:less_than_or_equal_to] = attr['maximum'] if attr['maximum'].present?
  opts[:less_than] = attr['exclusiveMinimum'] if attr['exclusiveMinimum'].present?
  opts[:greater_than] = attr['exclusiveMaximum'] if attr['exclusiveMaximum'].present?
  opts
end

#validate_with(schema, opts = {}) ⇒ Object

Parameters:

  • schema (Symbol|String)

    name

  • opts (Hash<Symbol|String>) (defaults to: {})


42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/schema_tools/modules/validations.rb', line 42

def validate_with(schema, opts={})
  reader = opts[:reader] || SchemaTools::Reader
  schema = reader.read(schema, opts[:path])
  # make getter / setter
  schema[:properties].each do |key, val|
    validates_length_of key, validate_length_opts(val) if val['maxLength'] || val['minLength']
    validates_presence_of key if val['required'] || val['required'] == 'true'
    validates_numericality_of key, validate_number_opts(val) if val['type'] == 'number'
    #TODO array minItems, max unique,  null, string
    # format: date-time, regex color style, email,uri,  ..
    validates_numericality_of key, validate_number_opts(val) if val['type'] == 'number'
    #end
  end
end