Class: Argo::SchemaFactory

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/argo/schema_factory.rb

Constant Summary collapse

NON_SUBSCHEMA_PROPERTIES =
%w[
  $schema
  additionalItems
  additionalProperties
  description
  id
  properties
  required
  title
  type
]

Instance Method Summary collapse

Constructor Details

#initialize(dereferencer) ⇒ SchemaFactory

Returns a new instance of SchemaFactory.



9
10
11
# File 'lib/argo/schema_factory.rb', line 9

def initialize(dereferencer)
  @dereferencer = dereferencer
end

Instance Method Details

#build(subgraph, route = []) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/argo/schema_factory.rb', line 15

def build(subgraph, route = [])
  Schema.new(
    description: extract_one(subgraph, :description),
    title: extract_one(subgraph, :title),
    schemas: subschemas(subgraph, route),
    type: type(subgraph),
    properties: properties(subgraph),
    spec: extract_one(subgraph, :$schema),
    route: route
  )
end

#element_kind(key) ⇒ Object



39
40
41
# File 'lib/argo/schema_factory.rb', line 39

def element_kind(key)
  NON_SUBSCHEMA_PROPERTIES.include?(key) ? key.to_sym : :subschema
end

#extract(subgraph, kind) ⇒ Object



43
44
45
# File 'lib/argo/schema_factory.rb', line 43

def extract(subgraph, kind)
  subgraph.select { |k, _| element_kind(k) == kind }
end

#extract_one(subgraph, kind, default: nil) ⇒ Object



47
48
49
50
# File 'lib/argo/schema_factory.rb', line 47

def extract_one(subgraph, kind, default: nil)
  _, v = subgraph.find { |k, _| element_kind(k) == kind }
  v || default
end

#properties(subgraph) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/argo/schema_factory.rb', line 61

def properties(subgraph)
  required_fields = extract_one(subgraph, :required, default: [])
  factory = PropertyFactory.new(@dereferencer, required_fields)
  extract_one(subgraph, :properties, default: {}).
    map { |k, v|
      [k, reference?(v) ? dereference(v) : factory.build(v, name: k)]
    }.
    to_h
end

#subschemas(subgraph, route) ⇒ Object



52
53
54
55
# File 'lib/argo/schema_factory.rb', line 52

def subschemas(subgraph, route)
  extract(subgraph, :subschema).
    inject({}) { |h, (k, v)| h.merge(k => build(v, route + [k])) }
end

#type(subgraph) ⇒ Object



57
58
59
# File 'lib/argo/schema_factory.rb', line 57

def type(subgraph)
  extract_one(subgraph, :type, default: :object).to_sym
end