Module: Square::Internal::Types::Union

Includes:
Type
Included in:
Boolean, Types::CatalogObject
Defined in:
lib/square/internal/types/union.rb

Overview

Define a union between two types

Instance Method Summary collapse

Methods included from Type

#strict!, #strict?

Methods included from JSON::Serializable

#dump, #load

Instance Method Details

#coerce(value, strict: strict?) ) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/square/internal/types/union.rb', line 61

def coerce(value, strict: strict?)
  type = resolve_member(value)

  unless type
    return value unless strict

    if discriminated?
      raise Errors::TypeError,
            "value of type `#{value.class}` not member of union #{self}"
    end

    raise Errors::TypeError, "could not resolve to member of union #{self}"
  end

  Utils.coerce(type, value, strict: strict)
end

#discriminant(key) ⇒ void

This method returns an undefined value.

Set the discriminant for this union

Parameters:

  • key (Symbol, String)


32
33
34
# File 'lib/square/internal/types/union.rb', line 32

def discriminant(key)
  @discriminant = key
end

#member(type, key: nil) ⇒ void

This method returns an undefined value.

Add a member to this union

Parameters:

  • type (Object)
  • key (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (key:):

  • (Symbol, String)


19
20
21
22
# File 'lib/square/internal/types/union.rb', line 19

def member(type, key: nil)
  members.push([key, Utils.wrap_type(type)])
  self
end

#member?(type) ⇒ Boolean

Returns:



24
25
26
# File 'lib/square/internal/types/union.rb', line 24

def member?(type)
  members.any? { |_key, type_fn| type == type_fn.call }
end

#membersObject



10
11
12
# File 'lib/square/internal/types/union.rb', line 10

def members
  @members ||= []
end