Class: SoberSwag::Serializer::Optional
- 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
-
#inner ⇒ SoberSwag::Serializer::Base
readonly
The serializer to use for non-nil values.
Instance Method Summary collapse
- #finalize_lazy_type! ⇒ Object
-
#initialize(inner) ⇒ Optional
constructor
A new instance of Optional.
- #lazy_type ⇒ Object
- #lazy_type? ⇒ Boolean
-
#optional ⇒ void
Since nesting optional types is bad, this will always raise an ArgumentError.
-
#serialize(object, options = {}) ⇒ Object
If
object
is nil, returnnil
. - #type ⇒ Object
Methods inherited from Base
#array, #identifier, #meta, #serializer, #via_map
Constructor Details
#initialize(inner) ⇒ Optional
Returns a new instance of Optional.
16 17 18 |
# File 'lib/sober_swag/serializer/optional.rb', line 16 def initialize(inner) @inner = inner end |
Instance Attribute Details
#inner ⇒ SoberSwag::Serializer::Base (readonly)
Returns the serializer to use for non-nil values.
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_type ⇒ Object
28 29 30 |
# File 'lib/sober_swag/serializer/optional.rb', line 28 def lazy_type @inner.lazy_type.optional end |
#lazy_type? ⇒ Boolean
24 25 26 |
# File 'lib/sober_swag/serializer/optional.rb', line 24 def lazy_type? @inner.lazy_type? end |
#optional ⇒ void
This method returns an undefined value.
Since nesting optional types is bad, this will always raise an ArgumentError
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, = {}) if object.nil? object else inner.serialize(object, ) end end |
#type ⇒ Object
47 48 49 |
# File 'lib/sober_swag/serializer/optional.rb', line 47 def type inner.type.optional end |