LoginSignup
7
2

Ruby on RailsのDEPRECATION WARNINGの出力先を設定するactive_support.deprecation

Posted at

Railsをバージョンアップするときに、DEPRECATION WARNINGが出ることがあります。
この警告は「今回のバージョンアップでは影響がないが将来的に無効になる機能」を教えてくれます。

DEPRECATION WARNING の例

例えば Rails 7.1 にバージョンを上げたときに、次の警告が表示されることがあります。

DEPRECATION WARNING: Passing the coder as positional argument is deprecated and will be removed in Rails 7.2.

Please pass the coder as a keyword argument:

  serialize :namespaces, coder: Psych
 (called from <class:Project> at /home/runner/work/pubannotation/pubannotation/app/models/project.rb:6)

現在は次のように、ActiveRecordのserializeメソッドの第二引数でcoderを指定出来ます。

def serialize(attr_name, class_name_or_coder = nil, coder: nil, type: Object, yaml: {}, **options)
 unless class_name_or_coder.nil?
   if class_name_or_coder == ::JSON || [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
     ActiveRecord.deprecator.warn(<<~MSG)
       Passing the coder as positional argument is deprecated and will be removed in Rails 7.2.

       Please pass the coder as a keyword argument:

         serialize #{attr_name.inspect}, coder: #{class_name_or_coder}
     MSG
     coder = class_name_or_coder
   else

これが、Rails 7.2では使えなくなる予定であることを教えてくれています。
対応はメッセージの通りです。代わりにキーワード引数を使います。
例えば、次のクラスのようにserializeの第二引数でYAMLの値を指定しているのであれば

class Project < ActiveRecord::Base
  serialize :namespaces, YAML

次のようにcoder:YAMLの前に追加します。

class Project < ActiveRecord::Base
  serialize :namespaces, coder: YAML

DEPRECATION WARNING が出る条件

rails consolerails serverで起動した時に、前述の警告に気がつきませんでした。
CI上のテスト結果を確認しているときに初めて気がつきました。
というのは、DEPRECATION WARNINGは環境変数RAILS_ENVdevelopmentのときは表示されないからです。
環境変数RAILS_ENVtestのときはターミナルに表示されます。そのためCIで実行したテスト結果では表示されます。

なぜ環境変数によって表示非表示が変わるのでしょうか?
表題の設定active_support.deprecationの値によります。

通常、config/environments/development.rbconfig/environments/test.rbactive_support.deprecationが設定されています。

active_support.deprecation とは

Rails アプリケーションの設定項目 - Railsガイド に次のように記述されています。

3.14.12 config.active_support.deprecation
非推奨警告メッセージの振る舞いを設定します。指定可能なオプションについてはDeprecation::Behaviorを参照してください。

デフォルトで生成されるconfig/environments以下のファイルでは、development環境では:logが、test環境では:stderrがそれぞれ設定されます。production環境ではこの設定は無視され、config.active_support.report_deprecationsの設定が使われます。

config/environments/development.rbactive_support.deprecation:logが設定されています。このため、development環境ではログに出力されます。ターミナルには表示されません。

また、これはデフォルト設定です。
rails app:updateコマンドを実行して、config/environments/development.rbファイルを更新すると、active_support.deprecationの値は:logになります。

教訓

Railsのバージョンアップをするときには、テストを実行して DEPRECATION WARNING が出ていないことを確認しましょう。

次回、Railsのバージョンアップをするときには、この教訓を忘れていると思います。ググってこの記事にたどり着いて「そういえば、そうだった!」と思い出すところまでがセットです。そのためにこの記事をセットしておきます。

参考

7
2
0

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
7
2