0
0

More than 3 years have passed since last update.

Railsのactionのfilter(before_actionとか)で沼にハマった

Last updated at Posted at 2020-08-31
  • 20分くらいハマった。

やったこと

  • それぞれのfilterにかかった時間を図るために、print_start_timeprint_end_timeを複数回呼び出す設定にしようとした。
my_controller.rb
class MyController < ApplicationController
  before_action :print_start_time
  before_action :action1
  before_action :print_end_time

  before_action :print_start_time
  before_action :action2
  before_action :print_end_time

  def print_start_time
    puts('### start time ###')
    puts(Time.now)
  end

  def print_end_time
    puts('### end time ###')
    puts(Time.now)
  end

  def action1
    ...
  end

  def action2
    ...
  end
end

どうなった?

挟み込まれたfilterは以下のようになった
(binding.pryで止めて_process_action_callbacksでfilterを順々に見れる)

> _process_action_callbacks.send(:chain).map{|c|puts "#{c.kind} - #{c.filter}"} 

before - action1
before - print_start_time
before - action2
before - print_end_time

つまり?

  • 同じfilterを複数回呼ぶと、callbackが後の場所に再定義され、元々定義されたものは消えてしまうようだ。

参考

looking at implementation of AbstractController::Callbacks, it can be seen they are created using define_method so it's expected that next call will redefine the callback. so I guess it's expected behaviour

Calling the same filter multiple times with different options will not work, since the last filter definition will overwrite the previous ones.

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