Class: CSV2Avro::SchemaValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/csv2avro/schema_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSchemaValidator

Returns a new instance of SchemaValidator.



8
9
10
# File 'lib/csv2avro/schema_validator.rb', line 8

def initialize
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



6
7
8
# File 'lib/csv2avro/schema_validator.rb', line 6

def errors
  @errors
end

Instance Method Details

#clearObject



12
13
14
# File 'lib/csv2avro/schema_validator.rb', line 12

def clear
  @errors.clear
end

#validate(expected_schema, datum, name = nil, suppress_error = false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/csv2avro/schema_validator.rb', line 16

def validate(expected_schema, datum, name=nil, suppress_error=false)
  expected_type = expected_schema.type_sym

  valid = case expected_type
          when :null
            datum.nil?
          when :boolean
            datum == true || datum == false
          when :string, :bytes
            datum.is_a? String
          when :int
            (datum.is_a?(Fixnum) || datum.is_a?(Bignum)) &&
                (Avro::Schema::INT_MIN_VALUE <= datum) && (datum <= Avro::Schema::INT_MAX_VALUE)
          when :long
            (datum.is_a?(Fixnum) || datum.is_a?(Bignum)) &&
                (Avro::Schema::LONG_MIN_VALUE <= datum) && (datum <= Avro::Schema::LONG_MAX_VALUE)
          when :float, :double
            datum.is_a?(Float) || datum.is_a?(Fixnum) || datum.is_a?(Bignum)
          when :fixed
            datum.is_a?(String) && datum.size == expected_schema.size
          when :enum
            expected_schema.symbols.include? datum
          when :array
            datum.is_a?(Array) &&
              datum.all?{|d| validate(expected_schema.items, d) }
          when :map
            datum.keys.all?{|k| k.is_a? String } &&
              datum.values.all?{|v| validate(expected_schema.values, v) }
          when :union
            expected_schema.schemas.any?{|s| validate(s, datum, nil, true) }
          when :record, :error, :request
            datum.is_a?(Hash) &&
              expected_schema.fields.reduce(true){|result, f|
              validate_result = validate(f.type, datum[f.name], f.name)
              result && validate_result }
          else
            false
          end

  if !valid && name
    if datum.nil? && expected_type != :null
      @errors << "Missing value at #{name}"
    else
      @errors << "'#{datum}' at #{name} doesn't match the type '#{expected_schema.to_s}'"
    end
  end

  valid
end