Sha256: 5dec277610c6b2483709a6a0f5bc487f1605509abc5d1d22b5214a02c1e2bc64

Contents?: true

Size: 1.84 KB

Versions: 3

Compression:

Stored size: 1.84 KB

Contents

# frozen_string_literal: true

require 'json_schemer/version'
require 'json_schemer/format'
require 'json_schemer/cached_ref_resolver'
require 'json_schemer/schema/base'
require 'json_schemer/schema/draft4'
require 'json_schemer/schema/draft6'
require 'json_schemer/schema/draft7'

module JSONSchemer
  class UnsupportedMetaSchema < StandardError; end
  class UnknownRef < StandardError; end
  class InvalidFileURI < StandardError; end
  class InvalidSymbolKey < StandardError; end

  DRAFT_CLASS_BY_META_SCHEMA = {
    'http://json-schema.org/draft-04/schema#' => Schema::Draft4,
    'http://json-schema.org/draft-06/schema#' => Schema::Draft6,
    'http://json-schema.org/draft-07/schema#' => Schema::Draft7
  }.freeze

  DEFAULT_META_SCHEMA = 'http://json-schema.org/draft-07/schema#'

  FILE_URI_REF_RESOLVER = proc do |uri|
    raise InvalidFileURI, 'must use `file` scheme' unless uri.scheme == 'file'
    raise InvalidFileURI, 'cannot have a host (use `file:///`)' if uri.host
    JSON.parse(File.read(uri.path))
  end

  class << self
    def schema(schema, **options)
      case schema
      when String
        schema = JSON.parse(schema)
      when Pathname
        uri = URI.parse("file://#{schema.realpath}")
        if options.key?(:ref_resolver)
          schema = FILE_URI_REF_RESOLVER.call(uri)
        else
          ref_resolver = CachedRefResolver.new(&FILE_URI_REF_RESOLVER)
          schema = ref_resolver.call(uri)
          options[:ref_resolver] = ref_resolver
        end
        schema[draft_class(schema)::ID_KEYWORD] ||= uri.to_s
      end
      draft_class(schema).new(schema, **options)
    end

  private

    def draft_class(schema)
      meta_schema = schema.is_a?(Hash) && schema.key?('$schema') ? schema['$schema'] : DEFAULT_META_SCHEMA
      DRAFT_CLASS_BY_META_SCHEMA[meta_schema] || raise(UnsupportedMetaSchema, meta_schema)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
json_schemer-0.1.8 lib/json_schemer.rb
json_schemer-0.1.7 lib/json_schemer.rb
json_schemer-0.1.6 lib/json_schemer.rb