DEV Community

hiko1129
hiko1129

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

[Ruby][Sorbet] Write also the type of the side that depends on the type definition of concerns, safely and cleanly

Translate ja to en

最近concernsの型定義には下記のように依存する側の型も書くようにしてる。

module Hoge
  extend T::Sig
  extend ActiveSupport::Concern

  Includer = T.type_alias {T.all(Hoge, Fuga)} # 依存する側のFugaクラスを追加してHogeとFugaの交差型に
  private_constant :Includer

  sig { returns(String) }
  def hoge
    'hoge'
  end

  sig { returns(String) }
  def hoge_fuga
    includer.hoge + includer.fuga # includerは自身とFugaクラスの交差型なので、自身のhogeメソッドも見えるし、Fugaにあるfugaメソッドも参照できる
  end

  private

    sig { returns(Includer) }
    def includer # 名前が適切かと聞かれたら微妙だが、とりあえず自身と依存する側両方の型を返すメソッドを用意してこれに依存してメソッド呼び出す形にすることできれいに書ける
      T.bind(self, Includer)
      self
    end
end

class Fuga
  extend T::Sig

  sig { returns(String) }
  def fuga
    'fuga'
  end
end
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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