Class: Validator::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/opennebula/flow/validator.rb

Overview

The Validator class is used to validate a JSON body based on a schema which is a Hash that describes the structure of the body.

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Validator

Returns a new instance of Validator.

Parameters:

  • opts (Hash) (defaults to: {})

    the options to validate a body

Options Hash (opts):

  • :default_values (Boolean)

    Set default values if the schema specifies it (if true)

  • :delete_extra_properties (Boolean)

    If the body contains properties not specified in the schema delete them from the body (if true) or raise an exception (if false)

  • :allow_extra_properties (Boolean)

    Allow properties not specified in the schema



118
119
120
121
122
123
124
# File 'lib/opennebula/flow/validator.rb', line 118

def initialize(opts = {})
    @opts = {
        :default_values => true,
        :delete_extra_properties => false,
        :allow_extra_properties => false
    }.merge(opts)
end

Instance Method Details

#validate!(body, schema, key = '') ⇒ Hash, ...

Note:

The parameter body will be modified

Note:

Schema options supported :extends :type => [:object, :array, :string, :null]

Recursively validate and modify a JSON body based on a schema.

Examples:

Validate a User

schema = {
    :type => :object,
    :properties => {
        'username' => {
            :type => :string
        }
    }
}

hash = {
    'username' => 'pepe'
}

Validator.validate!(hash, schema)
#=> {'username' => 'pepe'}

Parameters:

  • body (Hash, Array, String, nil)

    JSON represented as Ruby objects

  • schema (Hash)

    that will be used to validate

  • key (String) (defaults to: '')

    of the body that will be validated in this step

Returns:

  • (Hash, Array, String, nil)

    The modified body

Raises:

See Also:



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/opennebula/flow/validator.rb', line 161

def validate!(body, schema, key = '')
    if schema[:extends]
        base_schema = schema.delete(:extends)
        schema      = base_schema.deep_merge(schema)
    end

    case schema[:type]
    when :object  then validate_object(body, schema, key)
    when :array   then validate_array(body, schema, key)
    when :string  then validate_string(body, schema, key)
    when :integer then validate_integer(body, schema, key)
    when :null    then validate_null(body, schema, key)
    when :boolean then validate_boolean(body, schema, key)
    else raise SchemaException, "Unsupported type #{schema[:type]}"
    end
end