module Dryv::Schema

Attributes

attributes[R]
errors[R]

Public Class Methods

new(params) click to toggle source
# File lib/dryv/schema.rb, line 6
def initialize(params)
  @errors     = Dryv::Errors.new
  @attributes = cast({ wrap: params }.deep_symbolize_keys[:wrap], schema)
  JSON::Validator.validate!(schema, attributes)
end

Public Instance Methods

[](key) click to toggle source
# File lib/dryv/schema.rb, line 13
def [](key)
  attributes[key.to_sym]
end
schema() click to toggle source
# File lib/dryv/schema.rb, line 25
def schema
  raise NotImplemented
end
valid?() click to toggle source
# File lib/dryv/schema.rb, line 18
def valid?
  validate_attributes(attributes, schema)
  validate_additional
  !errors.any?
end

Private Instance Methods

cast(params, schema) click to toggle source
# File lib/dryv/schema.rb, line 73
def cast(params, schema)
  props = schema.is_a?(Hash) && schema[:cast] ? schema[:cast].call(params) : params

  case props
    when Hash
      props.each_with_object({}) do |(key, value), result|
        result[key] = find_schemas_for_attribute(key, schema).inject((value.dup rescue value)) do
          |_value, _schema| _value = cast(_value, _schema); _value
        end
      end
    when Array
      props.map { |e| cast(e, (schema[:items] rescue nil)) }
    else
      props
  end
validate_additional() click to toggle source
# File lib/dryv/schema.rb, line 33
def validate_additional
end
validate_attributes(props, schema, parents = [], key = nil) click to toggle source
# File lib/dryv/schema.rb, line 37
def validate_attributes(props, schema, parents = [], key = nil)
  case props
    when Dryv::Schema
      errors.merge!(props.errors, (parents + [key]).compact.join('.')) unless props.valid?
    else
      [schema[:rule]].flatten.compact.each do |rule|
        rule = rule.arity == 0 ? rule(key, parents, &rule) : rule.call(parents)
        rule.valid? if rule
      end
  end

  if schema[:properties]
    (schema[:properties] || {}).each do |_key, data|
      validate_attributes((props.present? ? props : {})[_key.to_sym], data, (parents + [key]).compact, _key)
    end
  elsif schema[:items]
    (props.present? ? props : []).each_with_index do |e, i|
      validate_attributes(e, schema[:items], (parents + [key]).compact, i)
    end
  end

  if schema[:oneOf] || schema[:allOf] || schema[:anyOf]
    [:oneOf, :allOf, :anyOf].each do |k|
      s = schema[k]
      case s
        when Hash
          validate_attributes(props, s, parents, key)
        when Array
          s.each { |_s| validate_attributes(props, _s, parents, key) if _s.is_a?(Hash) }
        else
      end
    end
  end
end