[Rails][Sorbet] sorbet-railsを使う際はTypedParamsを使うべし

sorbet-railsでは、下記のようにTypedParamsを使うことで簡単にController上でparamsをstructにマッピングする形でcastができます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class HogeController < ApplicationController
  class CreateParams < T::Struct
    const :name, String
  end

  private_constance :CreateParams

  sig { void }
  def create
    typed_params = TypedParams[CreateParams].new.extract!(params)

    # typed_params.name -> String
  end
end

自分は見逃していて愚直にT.castをひたすら書いていました…

TypedParamsのもとになっているsorbet-coerceも使うとjsonカラム使うときに捗ります。

sorbet-coerceは下記のような感じで使えます。

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

json_column_value = {id: '1'}

TypeCoerce[Json].new.from(json_column_value)

結構Ruby(Rails)で型使えてます。

ref

Built with Hugo
テーマ StackJimmy によって設計されています。