[Rails][Sorbet] T::EnumでRailsのenumを定義する

T::Enumからindex付きのhashに変換するやつを書いてRailsのenum設定に使っています。
sorbet-rails使っている場合には逆にenum書くと型定義できた気がする(自分の使っているバージョンだと破損しているのでよく知らず)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class AAA < ApplicationRecord
  extend T::Sig

  class A < T::Enum # 共通メソッドとしてto_symやto_hashはconcernsなりにあるとよいかと
    extend T::Sig

    enums do
      Hoge = new('hoge')
      Fuga = new('fuga')
      Piyo = new('piyo')
    end

    sig { returns(Symbol) }
    def to_sym
      serialize.to_sym
    end

    class << self
      extend T::Sig

      sig { returns(T::Hash[Symbol, Integer]) }
      def to_hash
        values.each.with_index.each_with_object({}) do |(item, idx), result|
          result[item.to_sym] = idx
        end
      end
    end
  end

  # AAA::A.to_hash => {:hoge=>0, :fuga=>1, :piyo=>2}
  enum a: A.to_hash

  sig { returns(A) }
  def deserialize_a
    A.deserialize(a)
  end
end
Built with Hugo
テーマ StackJimmy によって設計されています。