Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep unsupported union values as-is #53

Merged
merged 1 commit into from
Jun 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions lib/sorbet-coerce/converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ def _convert(value, type, raise_coercion_error)
false_idx = i if t.is_a?(T::Types::Simple) && t.raw_type == FalseClass
end

raise ArgumentError.new(
'the only supported union types are T.nilable and T::Boolean',
) unless (
return value unless (
(!true_idx.nil? && !false_idx.nil? && !nil_idx.nil?) || # T.nilable(T::Boolean)
(type.types.length == 2 && (
!nil_idx.nil? || (!true_idx.nil? && !false_idx.nil?) # T.nilable || T::Boolean
Expand Down
40 changes: 38 additions & 2 deletions spec/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ class UnsupportedCustomType
# Does not respond to new
end

class WithSupportedUnion < T::Struct
const :nilable, T.nilable(String)
const :nilable_boolean, T.nilable(T::Boolean)
end

class WithUnsupportedUnion < T::Struct
const :union, T.any(String, Integer)
end

let!(:param) {
TypeCoerce[Param].new.from({
id: 1,
Expand Down Expand Up @@ -144,12 +153,12 @@ class UnsupportedCustomType
context 'when the given T::Struct is invalid' do
class Param2 < T::Struct
const :id, Integer
const :info, T.any(Integer, String)
const :param, Param
end

it 'raises an error' do
expect {
TypeCoerce[Param2].new.from({id: 1, info: 1})
TypeCoerce[Param2].new.from({id: 1, info: {}})
}.to raise_error(ArgumentError)
end
end
Expand Down Expand Up @@ -192,6 +201,33 @@ class Param2 < T::Struct
end
end

context 'when given union types' do
context 'supported union types' do
it 'coerces correctly' do
coerced = TypeCoerce[WithSupportedUnion].new.from(
nilable: 2,
nilable_boolean: 'true'
)
expect(coerced.nilable).to eq('2')
expect(coerced.nilable_boolean).to eq(true)
end
end

context 'unsupported union types' do
it 'keeps the values as-is' do
coerced = TypeCoerce[WithUnsupportedUnion].new.from(union: 'a')
expect(coerced.union).to eq('a')

coerced = TypeCoerce[WithUnsupportedUnion].new.from(union: 2)
expect(coerced.union).to eq(2)

expect do
TypeCoerce[WithUnsupportedUnion].new.from(union: nil)
end.to raise_error(TypeError)
end
end
end

context 'when dealing with arries' do
it 'coreces correctly' do
expect(TypeCoerce[T::Array[Integer]].new.from(nil)).to eql []
Expand Down