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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️