Class: Yamo::Validator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ Validator

Returns a new instance of Validator.



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/yamo/validator.rb', line 14

def initialize(schema)
  @hook = nil

  metavalidator = Kwalify::MetaValidator.instance
  parser = Kwalify::Yaml::Parser.new(metavalidator)
  @schema = parser.parse_file(schema)
  
  if parser.errors and !parser.errors.empty?
    raise Yamo::ValidateError, parser.errors
  end

  @validator = Kwalify::Validator.new(@schema)
end

Instance Attribute Details

#hookObject

Returns the value of attribute hook.



12
13
14
# File 'lib/yamo/validator.rb', line 12

def hook
  @hook
end

#schemaObject (readonly)

Returns the value of attribute schema.



11
12
13
# File 'lib/yamo/validator.rb', line 11

def schema
  @schema
end

Instance Method Details

#load_and_validate_source(src, yaml, file) ⇒ Object



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
65
66
67
68
# File 'lib/yamo/validator.rb', line 36

def load_and_validate_source(src, yaml, file)
  errors = nil
  doc = nil
  
  if yaml
    parser = Kwalify::Yaml::Parser.new(validator)
    if file
      doc = parser.parse_file(src)
    else
      doc = parser.parse(src)
    end
    errors = parser.errors()
  else
    if file
      doc = eval(IO.readlines(src).join(""))
    else
      doc = eval(src)
    end

    if doc.class != Hash
      raise Yamo::ValidateError, "data did not produce a Hash"
    end

    doc = if @hook.respond_to?(:pre_validate) then @hook.pre_validate(doc) else doc end
    errors = @validator.validate(doc)
  end

  if errors and !errors.empty?
    raise Yamo::ValidateError, "\n#{file ? src : 'input'} did not validate:\n" + errors.join("\n")
  end

  if @hook.respond_to?(:post_validate) then @hook.post_validate(doc) else doc end
end