Class: Datacaster::ThenNode

Inherits:
Base
  • Object
show all
Defined in:
lib/datacaster/then_node.rb

Instance Method Summary collapse

Methods included from Mixin

#&, #*, #call, #call_with_runtime, #cast_errors, #i18n_key, #i18n_map_keys, #i18n_scope, #i18n_vars, #json_schema, #json_schema_attributes, #then, #with_context, #with_object_context, #with_runtime, #|

Constructor Details

#initialize(left, then_caster, else_caster = nil) ⇒ ThenNode

Returns a new instance of ThenNode.



3
4
5
6
7
# File 'lib/datacaster/then_node.rb', line 3

def initialize(left, then_caster, else_caster = nil)
  @left = left
  @then = then_caster
  @else = else_caster
end

Instance Method Details

#cast(object, runtime:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/datacaster/then_node.rb', line 15

def cast(object, runtime:)
  unless @else
    raise ArgumentError.new('Datacaster: use "a & b" instead of "a.then(b)" when there is no else-clause')
  end

  left_result = @left.with_runtime(runtime).(object)

  if left_result.valid?
    @then.with_runtime(runtime).(left_result.value)
  else
    @else.with_runtime(runtime).(object)
  end
end

#else(else_caster) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
# File 'lib/datacaster/then_node.rb', line 9

def else(else_caster)
  raise ArgumentError.new("Datacaster: double else clause is not permitted") if @else

  self.class.new(@left, @then, DefinitionDSL.expand(else_caster))
end

#inspectObject



52
53
54
# File 'lib/datacaster/then_node.rb', line 52

def inspect
  "#<Datacaster::ThenNode Then: #{@then.inspect} Else: #{@else.inspect}>"
end

#to_json_schemaObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/datacaster/then_node.rb', line 29

def to_json_schema
  unless @else
    raise ArgumentError.new('Datacaster: use "a & b" instead of "a.then(b)" when there is no else-clause')
  end

  left = @left.to_json_schema

  JsonSchemaResult.new(
    "oneOf" => [
      (@left & @then).to_json_schema,
      JsonSchemaResult.new("not" => left).apply(@else.to_json_schema)
    ]
  )
end

#to_json_schema_attributesObject



44
45
46
47
48
49
50
# File 'lib/datacaster/then_node.rb', line 44

def to_json_schema_attributes
  super.merge(
    required:
      @left.to_json_schema_attributes[:required] &&
        @else.to_json_schema_attributes[:required]
  )
end