Class: AnyVali::RefSchema

Inherits:
Schema
  • Object
show all
Defined in:
lib/anyvali/schemas/ref_schema.rb

Constant Summary

Constants inherited from Schema

Schema::RESERVED_METADATA_KEYS

Instance Attribute Summary collapse

Attributes inherited from Schema

#coerce_config, #constraints, #custom_validators, #default_value, #has_default, #kind, #metadata

Instance Method Summary collapse

Methods inherited from Schema

#coerce, #default, #describe, #export, #parse, #portable?, #refine, type_name, #with_metadata

Constructor Details

#initialize(ref:, **kwargs) ⇒ RefSchema

Returns a new instance of RefSchema.



7
8
9
10
# File 'lib/anyvali/schemas/ref_schema.rb', line 7

def initialize(ref:, **kwargs)
  @ref = ref
  super(kind: "ref", **kwargs)
end

Instance Attribute Details

#refObject (readonly)

Returns the value of attribute ref.



5
6
7
# File 'lib/anyvali/schemas/ref_schema.rb', line 5

def ref
  @ref
end

Instance Method Details

#safe_parse(input, path: [], context: nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/anyvali/schemas/ref_schema.rb', line 16

def safe_parse(input, path: [], context: nil)
  context ||= ValidationContext.new
  resolved = resolve(context)
  if resolved.nil?
    issues = [ValidationIssue.new(
      code: IssueCodes::UNSUPPORTED_SCHEMA_KIND,
      path: path,
      expected: @ref,
      received: "unresolved ref"
    )]
    return ParseResult.new(value: nil, issues: issues)
  end
  context.instance_variable_set(:@active_refs, {}) unless context.instance_variable_defined?(:@active_refs)
  active_refs = context.instance_variable_get(:@active_refs)
  key = "#{@ref}:#{input.object_id}"
  if active_refs[key]
    return ParseResult.new(value: nil, issues: [
      ValidationIssue.new(
        code: IssueCodes::INVALID_TYPE,
        path: path,
        expected: @ref,
        received: "recursive ref"
      )
    ])
  end
  active_refs[key] = true
  begin
    resolved.safe_parse(input, path: path, context: context)
  ensure
    active_refs.delete(key)
  end
end

#to_nodeObject



12
13
14
# File 'lib/anyvali/schemas/ref_schema.rb', line 12

def to_node
  { "kind" => "ref", "ref" => @ref }
end