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

Add support for named properties on T::Struct #80

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion lib/sorbet-coerce/converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,9 @@ def _build_args(args, type, raise_coercion_error, coerce_empty_to_nil)
end

props = type.props
key_lookup = props.map { |prop_name, prop_config| [prop_config.fetch(:name, prop_name).to_sym, prop_name] }.to_h
args.map { |name, value|
key = name.to_sym
key = key_lookup.fetch(name.to_sym, name.to_sym)
[
key,
(!props.include?(key) || value.nil?) ?
Expand Down
13 changes: 13 additions & 0 deletions spec/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ class TestEnum < T::Enum
end
end

class WithName < T::Struct
const :my_value, Integer, name: 'myValue'
end

class WithEnum < T::Struct
const :myenum, TestEnum
end
Expand Down Expand Up @@ -340,6 +344,15 @@ class Param2 < T::Struct
end
end

context 'when dealing with name' do
it 'coerces correctly' do
expect(TypeCoerce[WithName].new.from({myValue: 1}).my_value).to eq 1
expect(TypeCoerce[WithName].new.from({"myValue" => 1}).my_value).to eq 1
expect(TypeCoerce[WithName].new.from({my_value: 1}).my_value).to eq 1
expect(TypeCoerce[WithName].new.from({"my_value" => 1}).my_value).to eq 1
end
end

it 'works with T.untyped' do
expect(TypeCoerce[T.untyped].new.from(1)).to eql 1

Expand Down