[Ruby][Sorbet] sorbet-coerceを使用して型変換で楽をする

https://github.com/chanzuckerberg/sorbet-coerce 単体でのスター数は少ないですが、sorbet-railsがTypedParamsとして提供しているクラスが内部的にsorbet-coerceに依存しているのでsorbet-rails分足して評価して上げても良いような感じです。

sorbet-coerceは下記のような感じで値を特定の型(クラス)に変換します。
ランタイムレベル変換機能付きのT.castのようなイメージです。

1
2
3
4
5
6
7
8
TypeCoerce[T::Boolean].new.from('false') # => false

class Params < T::Struct
  const :id, Integer
  const :role, String, default: 'wizard'
end

TypeCoerce[Params].new.from({id: '1'}) # => <Params id=1, role="wizard">

v0系のバージョン通り絶賛開発中って感じで、T.anyについては制限がある状態です(機能追加のPRは既に出ているので解決は時間の問題の模様)

Sorbetを利用する場合は、下記のようにTypeCoerce(あるいはsorbet-railsのTypedParams)を利用してjsonをT::Structにdeserializeして、T::Structのserializeメソッドを利用してjson形式(hash形式、as_jsonと同様)にserializeする感じになっていくかと。

controller上

1
2
3
4
5
6
7
8
9
class HogeParams < T::Struct
  const :id, Integer
end

class Response < T::Struct
  const :hoge, String
end

typed_params = TypedParams[HogeParams].new.extract!(params) # => <HogeParams id=1>

jbuilder上

1
T.cast(@res, HogeController::Response)
Built with Hugo
テーマ StackJimmy によって設計されています。