Sha256: e6c2afa4cf26a880ee8044c9a01bcf8b1200096d4a4d485c21a53b0e519746c2

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

module Siren
module JSONSchema
class SchemaBuilder

  def initialize (&block)
    # @context = { type: "object", additionalProperties: false, properties: {} }
    singleton_class.class_exec(&block)
    schema = build()
    puts JSON.parse(schema.to_json).to_yaml
  end

  def number (min: nil, max: nil, excl: nil, mul: nil)
    { type: "number", minimum: min, maximum: max, exclusiveMaximum: excl, multipleOf: mul }.compact
  end

  def integer (min: nil, max: nil, excl: nil, mul: nil)
    { type: "integer", minimum: min, maximum: max, exclusiveMaximum: excl, multipleOf: mul }.compact
  end

  def bool ()
    { type: "boolean" }
  end

  alias boolean bool

  def null ()
    { type: "null" }
  end

  def string (pattern = nil, min: nil, max: nil)
    pattern = Regexp.escape(pattern) if pattern.is_a?(String)
    pattern = Regexp.new(pattern.map{|p|Regexp.escape(p)}.join("|")) if pattern.is_a?(Array)
    pattern = pattern.inspect[1..-2] if pattern.is_a?(Regexp)
    { type: "string", minLength: min, maxLength: max, pattern: pattern }.compact
  end

  def array (itemType, min: nil, max: nil, uniq: nil, extra: nil)
    { type: "array", items: itemType, minItems: min, maxItems: max, uniqueItems: uniq, additionalItems: extra}.compact
  end

  def hash (propType)
    { type: "object", additionalProperties: propType }.compact
  end

  def object (props, extra: false, required: nil)
    { type: "object", additionalProperties: extra, required: required, properties: props }.compact
  end

  def any (*options)
    { anyOf: options }
  end

end
end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
altaire-siren-0.1.4 lib/siren/schemabuilder.rb
altaire-siren-0.1.2 lib/siren/schemabuilder.rb