Class: SoberSwag::Serializer::Optional

Inherits:
Base
  • Object
show all
Defined in:
lib/sober_swag/serializer/optional.rb

Overview

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.

Defined Under Namespace

Classes: NestedOptionalError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#array, #identifier, #meta, #serializer, #via_map

Constructor Details

#initialize(inner) ⇒ Optional

Returns a new instance of Optional.

Parameters:



16
17
18
# File 'lib/sober_swag/serializer/optional.rb', line 16

def initialize(inner)
  @inner = inner
end

Instance Attribute Details

#innerSoberSwag::Serializer::Base (readonly)

Returns the serializer to use for non-nil values.

Returns:



22
23
24
# File 'lib/sober_swag/serializer/optional.rb', line 22

def inner
  @inner
end

Instance Method Details

#finalize_lazy_type!Object



32
33
34
# File 'lib/sober_swag/serializer/optional.rb', line 32

def finalize_lazy_type!
  @inner.finalize_lazy_type!
end

#lazy_typeObject



28
29
30
# File 'lib/sober_swag/serializer/optional.rb', line 28

def lazy_type
  @inner.lazy_type.optional
end

#lazy_type?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/sober_swag/serializer/optional.rb', line 24

def lazy_type?
  @inner.lazy_type?
end

#optionalvoid

This method returns an undefined value.

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

Raises:



56
57
58
# File 'lib/sober_swag/serializer/optional.rb', line 56

def optional(*)
  raise NestedOptionalError, 'no nesting optionals please'
end

#serialize(object, options = {}) ⇒ Object

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



39
40
41
42
43
44
45
# File 'lib/sober_swag/serializer/optional.rb', line 39

def serialize(object, options = {})
  if object.nil?
    object
  else
    inner.serialize(object, options)
  end
end

#typeObject



47
48
49
# File 'lib/sober_swag/serializer/optional.rb', line 47

def type
  inner.type.optional
end