LoginSignup
45
42

More than 5 years have passed since last update.

Rails controller内でのcallbackの順番

Posted at

callback一覧

Railsのcallbackといえばbefore_action(before_filter)等を思い浮かべると思うが、
以下の9つが利用可能らしい

  • before_action(before_filter)
  • around_action(around_filter)
  • after_action(after_filter)
  • prepend_before_action(prepend_before_filter)
  • prepend_around_action(prepend_around_filter)
  • prepend_after_action(prepend_after_filter)
  • append_before_action(append_before_filter)
  • append_around_action(append_around_filter)
  • append_after_action(append_after_filter)

検証

検証はこちらのリポジトリで行った

コード(概要)

  before_action :before
  around_action :around
  after_action :after
  append_before_action :append_before
  append_around_action :append_around
  append_after_action :append_after
  prepend_before_action :prepend_before
  prepend_around_action :prepend_around
  prepend_after_action :prepend_after

  def callback_method
    @array ||= []
    @array << method_name
  end

結果

@array == %w(prepend_around prepend_before before around append_before append_around append_after after prepend_after)

考察

before,around,afterは別々に管理されているのかと思っていたが、
process_actionというcallbackで同列に管理されているようだ
実際にコードを覗いてみると、AbstractController::Callbacksで定義されているようだ

参考

検証用リポジトリ
AbstractController::Callbacks
ActiveSupport::Callbacks

45
42
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
45
42