LoginSignup
8
1

More than 1 year has passed since last update.

rails7で`to_s`の引数にシンボルでフォーマットを指定するとDEPRECATION WARNINGが発生する(`DEPRECATION WARNING: Integer#to_s(:currency) is deprecated. Please use Integer#to_formatted_s(:currency) instead.`)理由と対応

Last updated at Posted at 2021-12-27

概要

rails7で1000.to_s(:currency)の様に、to_sの引数にシンボルでフォーマットを指定するとDEPRECATION WARNINGが発生するようになりました。

DEPRECATION WARNING: Integer#to_s(:currency) is deprecated. Please use Integer#to_formatted_s(:currency) instead.

この変更はこちらのPRで追加されています。

理由

ruby3.1でsymbol, true, false, nil, 0-9へのto_sメソッド使用時のパフォーマンスチューニングが行われました。

railsではactivesuportで複数クラスのto_sメソッドをオーバーライドしているためこの恩恵が受けられなくなってしまった様です。
これまでの実装である、引数に:currencyなどのシンボルを受け取り、そのシンボルをもとにフォーマットを動的に変更する処理はto_formatted_sでも実装されたため、そちらを使うようにそのためwarnignのメッセージで促されています。
to_sDEPRECATION WARNINGを出力するかruby実装のto_sを呼び出すかを判断する処理に変更されました。

解決方法

warnignのメッセージで書かれているより呼び出すメソッドが変更するだけです。

- 1000.to_s(:currency)
+ 1000.to_formatted_s(:currency)

to_formatted_sto_fsと言うメソッド名でも呼び出せるようにaliasが指定されています。

8
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1