Releases: chanzuckerberg/sorbet-coerce
v0.2.2
v0.2.1
v0.2.0
This release adds T::Coerce::Configuration
for configuring CoercionError
. We have CoercionError
, ShapeError
, or TypeError
when the coercion doesn't work successfully.
T::Coerce::CoercionError
(configurable)
It raises a coercion error when it fails to convert a value into the specified type (i.e. 'bad string args' to Integer
). This can be configured globally or at each call-site. When configured to true
, it will fill the result with nil
instead of raising the errors.
T::Coerce::Configuration.raise_coercion_error = false # default to true
We can use an inline flag to overwrite the global configuration:
T::Coerce[T.nilable(Integer)].new.from('abc', raise_coercion_error: false)
# => nil
T::Coerce::ShapeError
(NOT configurable)
It raises a shape error when the shape of the input does not match the shape of input type (i.e. '1' to T::Array[Integer]
or to T::Struct
). This cannot be configured and always raise an error.
TypeError
(configurable)
It raises a type error when the coerced input does not match the input type. This error is raised by Sorbet and can be configured through T::Configuration
.
v0.1.6
v0.1.5
v0.1.4
v0.1.3
v0.1.2
v0.1.1
Initial release v0.1.0
This gem works with Sorbet's static type checker and type definitions. It'll return a statically-typed object or throws T::CoercionError
if the coercion fails.
It provides a simple and generic way of coercing types in a sorbet-typed project. It is particularly useful when we're dealing with external API responses and controller parameters.
converted = T::Coerce[<Type>].new.from(<value>)
T.reveal_type(converted) # <Type>
The supported types include
- Simple Types (Integer, String, etc.)
- Custom Types: If the values can be coerced by
.new
T.nilable(<supported type>)
T::Array[<supported type>]
- Subclasses of
T::Struct
We don't support
T::Hash
(currently)T.any(<supported type>, ...)
: A union type other thanT.nilable