Class: JsonSchema::Validator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ Validator

Returns a new instance of Validator.


7
8
9
# File 'lib/json_schema/validator.rb', line 7

def initialize(schema)
  @schema = schema
end

Instance Attribute Details

#errorsObject

Returns the value of attribute errors


5
6
7
# File 'lib/json_schema/validator.rb', line 5

def errors
  @errors
end

Instance Method Details

#validate(data, fail_fast: false) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/json_schema/validator.rb', line 11

def validate(data, fail_fast: false)
  @errors = []
  @visits = {}
  @fail_fast = fail_fast

  # This dynamically creates the "strict_or_fast_and" method which is used
  # throughout the validator to combine the previous validation result with
  # another validation check.
  # Logic wise, we could simply define this method without meta programming
  # and decide every time to either call fast_and or strict_end.
  # Unfortunately this has a small overhead, that adds up over the runtime
  # of the validator – about 5% if we check @fail_fast everytime.
  # For more details, please see https://github.com/brandur/json_schema/pull/96
  and_operation = method(@fail_fast ? :fast_and : :strict_and)
  define_singleton_method(:strict_or_fast_and, and_operation)

  catch(:fail_fast) do
    validate_data(@schema, data, @errors, ['#'])
  end
  @errors.size == 0
end

#validate!(data, fail_fast: false) ⇒ Object


33
34
35
36
37
# File 'lib/json_schema/validator.rb', line 33

def validate!(data, fail_fast: false)
  if !validate(data, fail_fast: fail_fast)
    raise AggregateError.new(@errors)
  end
end