Module: Pinnacle::Internal::Types::Union

Overview

Define a union between two types

Instance Method Summary collapse

Methods included from Type

#strict!, #strict?

Methods included from JSON::Serializable

#dump

Instance Method Details

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



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/pinnacle/internal/types/union.rb', line 122

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

  coerced = Utils.coerce(type, value, strict: strict)

  # For discriminated unions, store the discriminant info on the coerced instance
  # so it can be injected back during serialization (to_h)
  if discriminated? && value.is_a?(::Hash) && coerced.is_a?(Model)
    discriminant_value = value.fetch(@discriminant, nil) || value.fetch(@discriminant.to_s, nil)
    if discriminant_value
      coerced.instance_variable_set(:@_fern_union_discriminant_key, @discriminant.to_s)
      coerced.instance_variable_set(:@_fern_union_discriminant_value, discriminant_value)
    end
  end

  coerced
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/pinnacle/internal/types/union.rb', line 32

def discriminant(key)
  @discriminant = key
end

#load(str) ⇒ Object

Parse JSON string and coerce to the correct union member type

Parameters:

  • str (String)

    JSON string to parse

Returns:

  • (Object)

    Coerced value matching a union member



155
156
157
# File 'lib/pinnacle/internal/types/union.rb', line 155

def load(str)
  coerce(::JSON.parse(str, symbolize_names: true))
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/pinnacle/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/pinnacle/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/pinnacle/internal/types/union.rb', line 10

def members
  @members ||= []
end