class SoberSwag::Serializer::Optional

Given something that serializes a type 'A', this can be used to make a serializer of type 'A | nil'.

Or, put another way, makes serializers not crash on nil values. If {#serialize} is passed nil, it will return `nil` immediately, and not try to call the serializer of {#inner}.

Attributes

inner[R]

@return [SoberSwag::Serializer::Base] the serializer to use for non-nil values.

Public Class Methods

new(inner) click to toggle source

@param inner [SoberSwag::Serializer::Base] the serializer to use for non-nil values

# File lib/sober_swag/serializer/optional.rb, line 16
def initialize(inner)
  @inner = inner
end

Public Instance Methods

finalize_lazy_type!() click to toggle source
# File lib/sober_swag/serializer/optional.rb, line 32
def finalize_lazy_type!
  @inner.finalize_lazy_type!
end
lazy_type() click to toggle source
# File lib/sober_swag/serializer/optional.rb, line 28
def lazy_type
  @inner.lazy_type.optional
end
lazy_type?() click to toggle source
# File lib/sober_swag/serializer/optional.rb, line 24
def lazy_type?
  @inner.lazy_type?
end
optional(*) click to toggle source

Since nesting optional types is bad, this will always raise an ArgumentError

@raise [NestedOptionalError] always @return [void] nothing, always raises.

# File lib/sober_swag/serializer/optional.rb, line 56
def optional(*)
  raise NestedOptionalError, 'no nesting optionals please'
end
serialize(object, options = {}) click to toggle source

If `object` is nil, return `nil`. Otherwise, call `inner.serialize(object, options)`.

# File lib/sober_swag/serializer/optional.rb, line 39
def serialize(object, options = {})
  if object.nil?
    object
  else
    inner.serialize(object, options)
  end
end
type() click to toggle source
# File lib/sober_swag/serializer/optional.rb, line 47
def type
  inner.type.optional
end