[Sorbet][Rails] ActionMailerの型の書き方(sorbet-railsを使っているとき)

paramsメソッドを使っているとき

withメソッドに直接型定義できないのでrbi側のwithメソッドに型を定義する

app/mailers/application_mailer.rb

1
2
3
4
5
6
7
8
class ApplicationMailer
  before_action :set_params

  private
    def set_params
      @fuga = params[:fuga]
    end
end

sorbet/rbi/shims/app/mailers/application_mailer.rbi

1
2
3
4
5
6
# typed: strong

class ApplicationMailer
  sig { params(fuga: String).returns(T.self_type) }
  def self.with(fuga:); end
end

sorbet-railsを使っているときの各mailerのメソッドの書き方

sorbet-railsを使っているときは、下記のようにメソッドに型定義を書けば型を生成してくれる。 引数の型はそのまま生成される型に引き継がれるが、戻り値の型は無視される(ActionMailerのインスタンスメソッドの戻り値の型は ActionMailer::MessageDelivery と決まっている。ActionMailerの厳密な挙動周りは忘れた…)

app/mailers/hoge_mailer.rb

1
2
3
4
5
6
7
class HogeMailer < ApplicationMailer
  extend T::Sig

  sig { params(to: String, url: String).void }
  def hoge(to:, url:)
  end
end

参考

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