DEV Community

hiko1129
hiko1129

Posted on • Originally published at note.hiko1129.com on

[Ruby][Sorbet] Use sorbet-coerce to make it easy with type conversion

Translate ja to en

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

sorbet-coerceは下記のような感じで値を特定の型(クラス)に変換します。

ランタイムレベル変換機能付きのT.castのようなイメージです。

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"> 
Enter fullscreen mode Exit fullscreen mode

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

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

controller上

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> 
Enter fullscreen mode Exit fullscreen mode

jbuilder上

T.cast(@res, HogeController::Response) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)