Class: JSONSchema

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

Constant Summary collapse

VALIDATE =
begin
  require "json-schema"
  true
rescue LoadError
  false
end

Instance Method Summary collapse

Constructor Details

#initialize(hash, validate: VALIDATE, definitions: {}) ⇒ JSONSchema

Returns a new instance of JSONSchema.



12
13
14
15
16
# File 'lib/genny/json_schema.rb', line 12

def initialize(hash, validate: VALIDATE, definitions: {})
  # TODO: ensure it's a valid schema if VALIDATE
  hash['definitions'] = (definitions || {}).merge(hash['definitions'] || {})
  super(hash)
end

Instance Method Details

#genny(additional_opts = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/genny/json_schema.rb', line 18

def genny(additional_opts = {})
  opts = Genny.symbolize(self.merge(additional_opts))
  return opts[:enum].sample if opts.has_key?(:enum)
  return schema_from_ref(opts[:'$ref']).genny if opts[:'$ref']

  klass = {
    "array" => Genny::Array,
    "boolean" => Genny::Boolean,
    "number" => Genny::Float,
    "object" => Genny::Hash,
    "integer" => Genny::Integer,
    "null" => Genny::NilClass,
    "string" => Genny::String,
    nil => Genny::Hash
  }[opts[:type]]
  raise "Cannot generate JSON Schema object of type '#{opts[:type]}'." unless klass.respond_to?(:genny)
  # Convert the JSONSchema items object into something Array.genny can cope with
  opts[:items] = (opts[:items].is_a?(::Array) ? opts[:items] : [opts[:items]].compact).map do |item|
    JSONSchema.new(item, definitions: opts[:definitions])
  end if klass == Genny::Array
  klass.genny(opts)
end