Help us understand the problem. What is going on with this article?

Rails controller内でのcallbackの順番

More than 3 years have passed since last update.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away