[rails]特定のcontrollerではbefore_actionをskipしたい
Ruby2.1.4, Rails4.1.7で確認。
タイトルだけだと少し分かりづらいのですが、ApplicationController内にbefore_actionで事前処理を設定している状態で、特定のcontrollerではbefore_actionをskipしたい、という場合の対応方法メモです。
before_actionにifオプションを指定して、条件チェック用のメソッドを定義します。
ApplicationControllerでは条件メソッドの戻り値がtrueになるようにしておき、skipしたいControllerでは条件メソッドをオーバーライドしてfalseを返すようにすればできました。
- ApplicationController
class ApplicationController < ActionController::Base
before_action :before_first, :before_second, if: :use_before_action?
private
def before_first
# 事前処理その1
end
def before_second
# 事前処理その2
end
# 条件チェック用のメソッド
def use_before_action?
true
end
end
- ApplicationControllerを継承したApi::PingController
class Api::PingController < ApplicationController
def index
head 200
end
private
# falseを返すようにオーバーライド
def use_before_action?
false
end
end
これでApi::PingControllerでのみbefore_actionをskipすることができました。
参考
- [Rails3 事始め: [Rails3] before_filter に条件を設定する](http://rails3try.blogspot.jp/2011/12/rails3-beforefilter.html)