before_action(旧 before_filter)はchainで複数指定することができます。
before_actionを複数指定したりaround_actionと組み合わせたりした場合の実行順序について確認しておきましょう。
以下のようにWorksControllerを定義しました。
class WorksController < ApplicationController around_action :around_works_1 before_action :before_works_1, :before_works_2 after_action :after_works_1 after_action :after_works_2 around_action :around_works_2 prepend_before_action :prepend_before_works prepend_after_action :prepend_after_works prepend_around_action :prepend_around_works # callback定義はログを出すだけ
ApplicationControllerにはこのように記載してあります。
class ApplicationController < ActionController::Base around_action :around_app_1 before_action :before_app after_action :after_app around_action :around_app_2 prepend_around_action :prepend_around_app prepend_before_action :prepend_before_app prepend_after_action :prepend_after_app # callback定義はログを出すだけ
この状態でworks#indexを表示すると、以下のような結果になります。
prepend_around_works start prepend_before_works prepend_before_app prepend_around_app start around_app_1 start before_app around_app_2 start around_works_1 start before_works_1 before_works_2 around_works_2 start Rendered text template (0.1ms) around_works_2 end after_works_2 after_works_1 around_works_1 end around_app_2 end after_app around_app_1 end prepend_around_app end prepend_after_app prepend_after_works prepend_around_works end
CallbackChainは単なる配列なので、記述するときも配列を常にイメージするとわかりやすいです。
callback定義時には以下のように配列に入っていきます。
- before_action
- beforeのcallback chainにappendされる
- after_action
- afterのcallback chainにappendされる
- around_action
- beforeとafterのcallback chainにそれぞれappendされる
- prepend_before_filter
- beforeのcallback chainにprependされる
- prepend_after_filter
- afterのchainにprependされる
- prepend_around_filter
- beforeとafterのchainにそれぞれprependされる
もちろん、継承関係にあるときは先に親クラスをロードするので、そちらが先に評価されます。
あとは、実行時に「beforeのchainを先頭からすべて実行 → actionを実行 → afterのchainを末尾からすべて実行」になると考えれば簡単です。
※Chainが途中で中断する仕組みは、Railsでbefore_filter/before_actionがアクションを中止する仕組みを読んでみるの記事で記載しています。