Connor Shea
Connor Shea

Reputation: 870

Adding Sorbet type signatures to attr_reader/attr_writer with multiple variables

I have an attr_reader that provides more than one variable, like so:

attr_reader :user, :series

I want to add a type signature to it, but Sorbet doesn't support multiple return types,

sig { returns(User, Series) }
attr_reader :user, :series

Is the only option to split them up like so?:

sig { returns(User) }
attr_reader :user
sig { returns(Series) }
attr_reader :series

Upvotes: 1

Views: 1304

Answers (1)

paracycle
paracycle

Reputation: 7850

Yes, the only option is to split up your attribute declarations, just like how you would have done if you were defining separate getter/setter methods for them, unless all your attributes are of the same type.

The reason for this is that Sorbet, in the DSL phase of its operation, actually uses the sig on an attr_reader/attr_writer/attr_accessor declaration to define the sig on the synthetic methods that are produced by those declarations. Thus, a single getter for attr_reader, a single setter for attr_writer and a getter/setter pair for attr_accessor are generated synthetically and the sigs are applied to them.

As a result of this, this would be valid:

sig { returns(String) }
attr_reader :some_string_attr, :other_string_attr

but this would not be:

sig { returns(String, User) }
attr_reader :some_string_attr, :some_user_attr

Upvotes: 2

Related Questions