DEV Community

hiko1129
hiko1129

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

[Rails][Sorbet] Define Rails enum using T::Enum

Translate ja to en

T::Enumからindex付きのhashに変換するやつを書いてRailsのenum設定に使っています。

sorbet-rails使っている場合には逆にenum書くと型定義できた気がする(自分の使っているバージョンだと破損しているのでよく知らず)。

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay