Class: VCAP::JsonSchema::HashSchema

Inherits:
BaseSchema show all
Defined in:
lib/vcap/json_schema.rb

Overview

Check that required keys are present, and that they validate

Defined Under Namespace

Classes: Field

Instance Method Summary collapse

Constructor Details

#initialize(kvs = {}) ⇒ HashSchema

Returns a new instance of HashSchema.

Raises:

  • (ArgumentError)


114
115
116
117
118
119
120
121
122
123
124
# File 'lib/vcap/json_schema.rb', line 114

def initialize(kvs={})
  raise ArgumentError, "Expected Hash, #{kvs.class} given" unless kvs.is_a?(Hash)
  # Convert symbols to strings. Validation will be performed against decoded json, which will have
  # string keys.
  @fields = {}
  for k, v in kvs
    raise ArgumentError, "Expected schema for key #{k}, got #{v.class}" unless v.kind_of?(BaseSchema)
    k_s = k.to_s
    @fields[k_s] = Field.new(k_s, v, false)
  end
end

Instance Method Details

#optional(name, schema) ⇒ Object



131
132
133
134
# File 'lib/vcap/json_schema.rb', line 131

def optional(name, schema)
  name_s = name.to_s
  @fields[name_s] = Field.new(name_s, schema, true)
end

#required(name, schema) ⇒ Object



126
127
128
129
# File 'lib/vcap/json_schema.rb', line 126

def required(name, schema)
  name_s = name.to_s
  @fields[name_s] = Field.new(name_s, schema, false)
end

#validate(dec_json) ⇒ Object

Raises:



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/vcap/json_schema.rb', line 136

def validate(dec_json)
  raise TypeError, "Expected instance of Hash, got instance of #{dec_json.class}" unless dec_json.kind_of?(Hash)

  missing_keys = []
  for k in @fields.keys
    missing_keys << k unless dec_json.has_key?(k) || @fields[k].optional
  end
  raise MissingKeyError, "Missing keys: #{missing_keys.join(', ')}" unless missing_keys.empty?

  for k, f in @fields
    next if f.optional && !dec_json.has_key?(k)
    begin
      f.schema.validate(dec_json[k])
    rescue ValidationError => ve
      ve.message = "'#{k}' => " + ve.message
      raise ve
    end
  end
end