Class: Jimmy::SchemerFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/jimmy/schemer_factory.rb

Overview

Factory class for making JSONSchemer::Schema::Base instances

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, *resolvers, cache_resolvers: true, **opts) ⇒ SchemerFactory

Returns a new instance of SchemerFactory.

Parameters:

  • schema (Schema, #as_json)
  • resolvers (Array<#resolve, 'net/http'>)
  • cache_resolvers (true, false) (defaults to: true)
  • opts (Hash)

    Options to be passed to JSONSchemer



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/jimmy/schemer_factory.rb', line 16

def initialize(schema, *resolvers, cache_resolvers: true, **opts)
  unless self.class.available?
    raise LoadError, 'Please add the json_schemer gem to your Gemfile'
  end

  @schema    = schema
  @resolvers = resolvers.map(&method(:cast_resolver))
  @options   = opts.dup

  return if @resolvers.empty?

  res = method(:resolve)
  res = JSONSchemer::CachedRefResolver.new(&res) if cache_resolvers
  @options[:ref_resolver] = res
end

Class Method Details

.available?true, false

Returns true if the json_schemer gem is loaded.

Returns:

  • (true, false)


8
9
10
# File 'lib/jimmy/schemer_factory.rb', line 8

def self.available?
  defined? ::JSONSchemer
end

Instance Method Details

#resolve(uri) ⇒ Hash{String => Object}?

Parameters:

Returns:

  • (Hash{String => Object}, nil)


41
42
43
44
45
46
47
48
49
# File 'lib/jimmy/schemer_factory.rb', line 41

def resolve(uri)
  @resolvers.each do |resolver|
    return resolver.call(uri) unless resolver.respond_to? :resolve

    schema = resolver.resolve(uri)
    return schema.as_json if schema
  end
  nil
end

#schemerJSONSchemer::Schema::Base

Get an instance of JSONSchemer::Schema::Base that can be used to validate JSON documents against the given Jimmy::Schema.

Returns:

  • (JSONSchemer::Schema::Base)


35
36
37
# File 'lib/jimmy/schemer_factory.rb', line 35

def schemer
  @schemer ||= JSONSchemer.schema(@schema.as_json, **@options)
end